相信大部分人都知道,txt文件有四种编码格式,"GBK", "UTF-8", "Unicode", "UTF-16BE",每一种编码格式的区分在于写入文件头的信息不同.为了避免读取乱码的现象,我们应该在读取文本之前先读取文件头信息,以便做出正确的读取编码方式.下面给出方法.
import java.io.*; public class Test { public static void main(String[] args) throws Exception { System.out.println("------读取电脑上不同编码的文件,并输出-------"); File f1=new File("iotest\\io.txt"); sop(f1); System.out.println("-------------"); File f2=new File("iotest\\io1.txt"); sop(f2); System.out.println("-------------"); File f3=new File("iotest\\io2.txt"); sop(f3); } public static String codeString(String fileName) throws Exception//该方法可以传入一个文件,获取该文件的编码格式 { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName)); int p = (bis.read() << 8) + bis.read(); String code = null; switch (p) { case 0xefbb: code = "UTF-8"; break; case 0xfffe: code = "Unicode"; break; case 0xfeff: code = "UTF-16BE"; break; default: code = "GBK"; } bis.close(); return code; } public static void sop(File file) throws Exception { BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file)); BufferedWriter bufw=new BufferedWriter(new OutputStreamWriter(System.out)); String code=codeString(file.getAbsolutePath()); byte[] buf=new byte[1024]; System.out.println("编码是:"+code); while(bis.read(buf)!=-1) { String line=new String(buf,code); bufw.write(line); bufw.flush(); } bis.close(); } }
结果:
------读取电脑上不同编码的文件,并输出-------