读取GBK格式文件乱码解决方法,gbk乱码,eclipse 设置的是
分享于 点击 7586 次 点评:83
读取GBK格式文件乱码解决方法,gbk乱码,eclipse 设置的是
eclipse 设置的是UTF-8格式,读取GBK格式文本,输出时会乱码。
此方法在读取时,判断文件编码格式(主要针对简体中文),读取文件,
输出文本可以避免乱码。
import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;public class fileUtil {/** * 读取文件乱码,原因一:可能读的时候编码格式不对,原因二:可能打印的时候编码格式不对 * 这里只针对第一种情况。在读取文件的时候,判断文件编码格式,按照固定编码格式读取文件 * 相对来说原因二的情况比较好解决。输出时编码转换就可以了。 * initBookEncode 方法判断文件编码格式,主要针对简体中文 * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub System.out.println(readFile("F:\\\\小说\\\\九百九十六章麻烦,还是麻烦!.txt")); } public static String readFile(String file) throws IOException{ File f=new File(file); FileInputStream fis=new FileInputStream(f); InputStreamReader isr = new InputStreamReader(fis,initBookEncode(fis)); BufferedReader reader = new BufferedReader(isr); StringBuffer sb=new StringBuffer(); String s; while((s=reader.readLine()) != null){ sb.append(s+"\\r\\n"); } reader.close(); isr.close(); fis.close(); return sb.toString(); }// public static void readFileByLines(String fileName) {// File file = new File(fileName);// BufferedReader reader = null;// try {// System.out.println("以行为单位读取文件内容,一次读一整行:");// System.out.println(new FileReader(file).getEncoding());// System.exit(0);// reader = new BufferedReader(new FileReader(file));// String tempString = null;// int line = 1;// // 一次读入一行,直到读入null为文件结束// while ((tempString = reader.readLine()) != null) {// // 显示行号// System.out.println("line " + line + ": " + tempString);// line++;// }// reader.close();// } catch (IOException e) {// e.printStackTrace();// } finally {// if (reader != null) {// try {// reader.close();// } catch (IOException e1) {// }// }// }// }/** * * @param ss 待转换文本 * @param code 编码 * @return 转换后的文本 */ static String changeToGBK(String ss,String code){ String temp=null; try { temp=new String(ss.getBytes(),code); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return temp; } //读取文件编码 public static String initBookEncode(FileInputStream fileInputStream) { String encode = "gb2312"; try{ byte[] head = new byte[3]; fileInputStream.read(head); if(head[0]==-17 && head[1]==-69 && head[2] ==-65) encode = "UTF-8"; else if (head[0] == -1 && head[1] == -2 ) encode = "UTF-16"; else if (head[0] == -2 && head[1] == -1 ) encode = "Unicode";// else// System.out.println(head[0]+","+head[1]+","+head[2]); }catch (IOException e) { System.out.println(e.getMessage()); } return encode; }}//该片段来自于http://byrx.net
用户点评