咱們作文本處理的時候的最經常使用的就是讀寫文件了,尤爲是讀取文件,不管是什麼文件,我都傾向於一次性將文本的原始內容直接讀取到內存中再作處理,固然,這須要你有一臺大內存的機器,內存不夠者……能夠一次讀取少部份內容,分屢次讀取。
讀取文件效率最快的方法就是一次全讀進來,不少人用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; } }