JAVA 打开文件乱码 解决办法

有些问题有时很奇怪,也很让人恼火,GBK、GB2312是什么编码,当然是汉字编码喽,而常常汉字编码不认识汉字,是不是让人恼火呢?

下面这部分代码的意思是打开D盘目录下的file_jiucool.txt文件 ,然后在控制台将其内容输出!

String Data_Path = "D:/file_jiucool.txt";
		File file = new File(Data_Path);
		String line= "";
		if(file.exists()){		
			FileReader reader = new FileReader(Data_Path);	
			BufferedReader bufferedreader= new BufferedReader(reader);
			while((line = bufferedreader.readLine())!=null){
					line = new String(line.getBytes(), "UTF-8");
					System.out.println(line);
				}
		}

上述代码中,设置为GBK、GB2312 时全部为乱码,设置为UTF-8时,最后一个汉字为乱码,是不是很让人郁闷?正确代码如下:

String Data_Path = "D:/file_jiucool.txt";
		File file = new File(Data_Path);
		String line= "";
		if(file.exists()){		
			//FileReader reader = new FileReader(Data_Path);	
			//BufferedReader bufferedreader= new BufferedReader(reader);
			InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
			BufferedReader bufferedreader = new BufferedReader(isr);
			while((line = bufferedreader.readLine())!=null){
					//line = new String(line.getBytes(), "UTF-8");
					System.out.println(line);
				}
		}

所以,在读取文件的时候就得进行编码设置,而不是读完文件输出时再设置编码!

6 Responses to “JAVA 打开文件乱码 解决办法”

  1. lovee AUSTRALIA Safari Mac OS says:

    在全世界推广U码wwwww

    [Reply]

  2. zwwooooo CHINA Mozilla Firefox Windows says:

    这是我看不懂的js

    [Reply]

  3. 太感谢楼主了,我正在网上找这方面的文章呢,算是缘分吧,竟然无意间走到了这个博客里,并且找到了问题的答案,现在问题解决了谢谢楼主!

    [Reply]

  4. 记忆盒子 CHINA Mozilla Firefox Windows says:

    不管用java还是其他,生成文件出现乱码,时常遇到的事情,有时候调试还真令人头痛,罪魁祸首就是那个文件编码了。

    [Reply]

    久酷 CHINA Mozilla Firefox Windows Reply:

    @记忆盒子, 确实是啊,最烦人的就是编码问题,有时GBK GB2312就是不认识中文 很让人郁闷!

    [Reply]

  5. [...] This post was mentioned on Twitter by jiucool.com, 热点风向标. 热点风向标 said: JAVA 打开文件乱码 解决办法 http://ff.im/-pqlv3 [...]

Leave a Reply

:wink: :-| :-x :twisted: :) 8-O :( :roll: :-P :oops: :-o :mrgreen: :lol: :idea: :-D :evil: :cry: 8) :arrow: :-? :?: :!:


正在读取数据……