试了下,txt文件是英文的话不乱码,但是是中文的话就会出现乱码。
public class test {
public static void main(String[] args){
readFile();
//System.out.println("");
}
public static void readFile(){
try {
File file=new File("d:\\lamp\\1.txt");
Reader in=new FileReader(file);
char[] ch=new char[20];
int len=-1;
StringBuffer sb=new StringBuffer();
while((len=in.read(ch))!=-1){
sb.append(new String(ch,0,len));
}
in.close();
System.out.println(sb);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
非常感谢!!!!!
如果你用的eclipse,键点击你的类,有个properties,点开,有个人text file encoding 默认default,选择other ,下拉列表,选择utf-8
这种一般都是文件和开发环境的编码方式不一致导致,看你文件存储的编码格式是否和你开发环境的编码一致。
你在读的时候设置字符串读取为UTF-8就可以了
如果回答对您有帮助,请采纳
这个是流的问题,流应该用字节流;字符流会默认你本地的编码;也可以制定流的编码为UTP-8
重新对你的得到的结果字符串进行编码试试