我有一個包含1億條記錄的文本文件。我使用非常古老的方式來閱讀文件,但它花了很長時間,無法完成,因爲內存不足的問題。我很感激,如果你能推薦使用Java或使用任何外部庫讀取文件最好和最佳的方式。(最終的解決辦法應減少消耗的時間)這是我的代碼,我上面所解釋的,什麼是使用java讀取文件的最有效方式?
BufferedReader reader = null;
List<String> fileLines = new ArrayList<String>();
String line = "";
reader = new BufferedReader(new java.io.FileReader(file));
while ((line = reader.readLine()) != null) {
fileLines.add(line);
}
reader.close();
return fileLines;
還用另一種方式,但結果是一樣的。
public static void fileReading(File file, Object executingClass, String methodName, int size) throws IOException {
try {
Method method = executingClass.getClass().getMethod(methodName, List.class);
BufferedReader reader = null;
List<String> fileLines = new ArrayList<String>();
String line = "";
reader = new BufferedReader(new java.io.FileReader(file));
int track = 0;
while ((line = reader.readLine()) != null) {
track++;
fileLines.add(line);
if (0 == track % size) {
method.invoke(executingClass, fileLines);
fileLines.clear();
}
}
if (!fileLines.isEmpty()) {
method.invoke(executingClass, fileLines);
fileLines.clear();
}
reader.close();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
嘗試處理記錄一前一後,不保存所有的人。 – Berger
您正試圖通過將每個行添加到列表中來將整個文件讀入內存。 Java的JVM默認有1GB的限制(儘管你可以增加它)。你爲什麼不能一次讀出每一行,做任何你需要的處理然後把它扔掉? – Michael
我已更新我的問題,請參閱。通過使用我的新方法,我一次獲得1000個字符串列表並處理它。 –