我們做文本處理的時候的最常用的就是讀寫文件了,尤其是讀取文件,不論是什麼文件,我都傾向於一次性將文本的原始內容直接讀取到內存中再做處理,當然,這需要你有一臺大內存的機器,內存不夠者……可以一次讀取少部分內容,分多次讀取。
讀取文件效率最快的方法就是一次全讀進來,很多人用readline()之類的方法,可能需要反覆訪問文件,而且每次readline()都會調用編碼轉換,降低了速度,所以,在已知編碼的情況下,按字節流方式先將文件都讀入內存,再一次性編碼轉換是最快的方式,典型的代碼如下:
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;
}
}