//一行一行读取txt文件 public static List<String> ReadText(String FilePath) throws IOException { //存储从txt文件读取的全部行 List<String> txtList = new ArrayList<String>(); //获取文件格式 String TextCode = GetTextCode(FilePath); //文件输入流 FileInputStream fis = new FileInputStream(FilePath); //输入流读取 InputStreamReader isr = new InputStreamReader(fis,TextCode); //缓冲字符输入流 BufferedReader br = new BufferedReader(isr); String line = ""; while((line = br.readLine()) != null) { txtList.add(line); } fis.close(); isr.close(); br.close(); return txtList; }
//获取text文件编码 public static String GetTextCode(String FilePath) throws IOException { BufferedInputStream bin = new BufferedInputStream(new FileInputStream(FilePath)); int p = (bin.read() << 8) + bin.read(); bin.close(); 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"; // 可读取ANSI的格式 } return code; }
原文:https://www.cnblogs.com/wangxingzhou/p/9992524.html