java代码
Posted 巫居树
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java代码相关的知识,希望对你有一定的参考价值。
//一行一行读取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; }
以上是关于java代码的主要内容,如果未能解决你的问题,请参考以下文章