您好,欢迎访问一九零五行业门户网

java读取txt文件乱码解决方法

java读取txt文件,如果编码格式不匹配,就会出现乱码现象。所以读取txt文件的时候需要设置读取编码。txt文档编码格式都是写在文件头的,在程序中需要先解析文件的编码格式,获得编码格式后,在按此格式读取文件就不会产生乱码了。(推荐:java视频教程)
java编码与txt编码对应:
示例:
package com.lfl.attachment; import java.io.bufferedreader; import java.io.file; import java.io.fileinputstream; import java.io.inputstream; import java.io.inputstreamreader; public class textmain { public static void main(string[] args) throws exception { string filepath = "d:/article.txt"; // string filepath = "d:/article333.txt"; // string filepath = "d:/article111.txt"; string content = readtxt(filepath); system.out.println(content); } /** * 解析普通文本文件 流式文件 如txt * @param path * @return */ @suppresswarnings("unused") public static string readtxt(string path){ stringbuilder content = new stringbuilder(""); try { string code = resolvecode(path); file file = new file(path); inputstream is = new fileinputstream(file); inputstreamreader isr = new inputstreamreader(is, code); bufferedreader br = new bufferedreader(isr); // char[] buf = new char[1024]; // int i = br.read(buf); // string s= new string(buf); // system.out.println(s); string str = ""; while (null != (str = br.readline())) { content.append(str); } br.close(); } catch (exception e) { e.printstacktrace(); system.err.println("读取文件:" + path + "失败!"); } return content.tostring(); } public static string resolvecode(string path) throws exception { // string filepath = "d:/article.txt"; //[-76, -85, -71] ansi // string filepath = "d:/article111.txt"; //[-2, -1, 79] unicode big endian // string filepath = "d:/article222.txt"; //[-1, -2, 32] unicode // string filepath = "d:/article333.txt"; //[-17, -69, -65] utf-8 inputstream inputstream = new fileinputstream(path); byte[] head = new byte[3]; inputstream.read(head); string code = "gb2312"; //或gbk if (head[0] == -1 && head[1] == -2 ) code = "utf-16"; else if (head[0] == -2 && head[1] == -1 ) code = "unicode"; else if(head[0]==-17 && head[1]==-69 && head[2] ==-65) code = "utf-8"; inputstream.close(); system.out.println(code); return code; } }
注意:在resolvetxt方法中不能通过readtxt方法传inputstream流 ,这样会使两个方法持有同一个流引用,而在resolvetxt方法中已读过流中的三个字节,流中的pos此时已经是3了,而不是流的起始位置,再在readtxt中读取时就会出现ioexception:read error。
更多java知识请关注java基础教程栏目。
以上就是java读取txt文件乱码解决方法的详细内容。
其它类似信息

推荐信息