我有一个文本文件。我想从一行到另一行检索内容。例如,文件可能有200K行。我想读取从第78行到第2735行的内容。由于文件可能非常大,我不想将整个内容读取到内存中。
发布于 2010-04-26 23:03:28
这是一个可能的解决方案的开始:
public static List<String> linesFromTo(int from, int to, String fileName)
throws FileNotFoundException, IllegalArgumentException {
return linesFromTo(from, to, fileName, "UTF-8");
}
public static List<String> linesFromTo(int from, int to, String fileName, String charsetName)
throws FileNotFoundException, IllegalArgumentException {
if(from > to) {
throw new IllegalArgumentException("'from' > 'to'");
}
if(from < 1 || to < 1) {
throw new IllegalArgumentException("'from' or 'to' is negative");
}
List<String> lines = new ArrayList<String>();
Scanner scan = new Scanner(new File(fileName), charsetName);
int lineNumber = 0;
while(scan.hasNextLine() && lineNumber < to) {
lineNumber++;
String line = scan.nextLine();
if(lineNumber < from) continue;
lines.add(line);
}
if(lineNumber != to) {
throw new IllegalArgumentException(fileName+" does not have "+to+" lines");
}
return lines;
}发布于 2010-04-26 22:52:36
使用BufferedReader.readLine()并计算行数。您将只在内存中保留缓冲区大小和当前行。
而且不可能在不读取整个文件的情况下到达第3412行(除非所有行都有固定的大小)。
发布于 2010-04-26 22:52:33
只需先逐行阅读并计算行数,然后从您提到的行位置开始获取所需的内容。
https://stackoverflow.com/questions/2714385
复制相似问题