【java新手求助】java读取txt出现乱码

现在有一个很小的程序,就是读取一个给定的txt文件。
我目前的状况是,txt文件如果直接通过java读取就都是乱码,除非是先用java生成一个txt文件然后再读取。
希望大家帮忙改下程序。。。

package lesson;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class c {
static String str;

static char[] charnum=new char[1024];
static int i=0;

public static void main(String[] args) {
File aFile = new File("D:/Java/example.txt");
FileInputStream inFile = null;

try {
inFile = new FileInputStream(aFile);

} catch(FileNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
}

FileChannel inChannel = inFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
try {
while(inChannel.read(buf) != -1) {
str= ((ByteBuffer)(buf.flip())).asCharBuffer().toString();
System.out.println(str);
System.out.println(new String(str.getBytes(),"UTF-8"));
buf.clear();
}
inFile.close();
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
}
}

首先你要清楚,文本文件是用什么字符集编码的,编码和解码的字符集不兼容时一定会出错(是一定哦)。
还得知道你的操作系统默认的字符集。比如你的windows用的是gbk。
你新建一个文本文件1.txt,打几个汉字保存,看它的大小是多少字节,记住这个数。这时的大小是用gbk编码的大小。
再打开这个文件,另存为,编码选择utf-8,覆盖这个文件,你能发现它比刚才大多了。因为编码集不一样了。
所以你用什么字符集编码就用什么字符集解码,这是任何情况下都应该遵守的。
别用你那个程序了。

InputStreamReader的构造方法是可以包含字符集的,像楼上说的那样,
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(你的文件名),文件的编码字符集)) 这个看api文档InputStreamReader的构造方法。
然后用br.readLine()读。
程序就不给你写了,很简单,就用这个方法。

再次强调,关于字符集只有两点好说的:
1.不同字符集编出来的文件大小不等。
2.文本文件的编码字符集和解码字符集要一致,否则一定会乱码。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-05-27
txt里默认的编码当然不是 utf了

你这样
System.out.println(new String(str.getBytes(),"UTF-8"));
不出乱码才怪

你把utf 换成别的的试试
第2个回答  2010-05-26
你是什么格式的文本啊 如果你不是utf-8文本格式的文本

System.out.println(new String(str.getBytes(),"UTF-8"));
这句话这里就会出错
第3个回答  推荐于2016-04-12
为什么这么麻烦呢。。java读取文件乱码的问题。。底层都已经封闭好了。。直接输出读取的数据就可以了。。
try {
byte a[] = new byte[inFile.available()] ;
if(inFile.read(a)!=-1)
{
inFile.read(a);
System.out.println (new String(a));

}
inFile.close();
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}本回答被提问者采纳
第4个回答  2010-05-27
为什么要转换utf-8呢?直接输出就应该是正常的
相似回答