a.txt:
大家好,我是刘德华
public class Main { public static void main(String[] args) throws IOException {
BufferedReader fin = null;
try {
fin = new BufferedReader(new FileReader("a.txt"));
String temp;
while((temp = fin.readLine()) != null)
println(temp);
} finally {
if(fin != null)
fin.close();
}
}
}
显示的是:
������ҵ����˾
。
大家好,我是刘德华
public class Main { public static void main(String[] args) throws IOException {
BufferedReader fin = null;
try {
fin = new BufferedReader(new FileReader("a.txt"));
String temp;
while((temp = fin.readLine()) != null)
println(temp);
} finally {
if(fin != null)
fin.close();
}
}
}
显示的是:
������ҵ����˾
。
println(temp); 这个println貌似是自己实现的吧,我用
while((temp = fin.readLine()) != null)
System.out.println(temp); 控制台打印出来的是正常的......这个把你println函数贴出来看看
貌似我的人品有问题???
我是英文版WIN都s7
BufferedReader reader = null;
File file = new File("a.txt");
try {
// 视文本文件实际保存编码不同,指定相应的编码格式, 比如:GBK,UTF-8...
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));
StringBuilder builder = new StringBuilder();
char[] chars = new char[4096];
int length = 0;
while (0 < (length = reader.read(chars))) {
builder.append(chars, 0, length);
}
return builder.toString();
} finally {
try {
if (reader != null) reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
参考:http://www.iscripts.org/bbs/viewthread.php?tid=33
后来看了别人的帖,发现是文件编码的问题。
比如你新建记事本文件,写几个汉字,然后另存为,编码有ansi,utf8,unicode,unicode big endian什么的。看他们的意思,好像是文件编码的问题。比如我的文本文件用utf8,那就没乱码,如果用别的,好像有乱码。
========================
PS:这个,不太懂,详情请看5楼吧
new BufferedReader (InputStreamReader(file,Charset.forName("GBK")));//"GBK GB2312等..." ok!给你一份我的代码分段,是处理来自web的字符串(这里的token 含中文乱码),因为传输过程它会用ISO-8859-1编码,所以我要指 定ISO-8859-1获取byte 为因我的是中文系统,所以可以不用显式指定中文编码,也不会乱码
if (token==null) return true;
byte[] bytes=token.getBytes(Charset.forName("ISO-8859-1"));
ByteBuffer bf=ByteBuffer.wrap(bytes);
CharBuffer cb=Charset.defaultCharset().decode(bf);
String s=new String(bytes);
System.out.println(s); //ok
System.out.println(cb.toString());//ok