咱们作文本处理的时候的最经常使用的就是读写文件了,尤为是读取文件,不管是什么文件,我都倾向于一次性将文本的原始内容直接读取到内存中再作处理,固然,这须要你有一台大内存的机器,内存不够者……能够一次读取少部份内容,分屡次读取。
读取文件效率最快的方法就是一次全读进来,不少人用readline()之类的方法,可能须要反复访问文件,并且每次readline()都会调用编码转换,下降了速度,因此,在已知编码的状况下,按字节流方式先将文件都读入内存,再一次性编码转换是最快的方式,典型的代码以下:html
public String readToString(String fileName) { String encoding = "UTF-8"; File file = new File(fileName); Long filelength = file.length(); byte[] filecontent = new byte[filelength.intValue()]; try { FileInputStream in = new FileInputStream(file); in.read(filecontent); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { return new String(filecontent, encoding); } catch (UnsupportedEncodingException e) { System.err.println("The OS does not support " + encoding); e.printStackTrace(); return null; } }