我有一个包含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个字符串列表并处理它。 –