- // 一行一行读取 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;
- }
来源: http://www.bubuko.com/infodetail-2854854.html