我有一个文本文件。我想将内容从一行检索到另一行。 例如,文件可能是200K行。我想从第78行到第2735行读取内容。由于文件可能非常大,我不想将整个内容读入内存。
答案 0 :(得分:12)
使用BufferedReader.readLine()并计算行数。你只会将缓冲区大小和当前行保留在内存中。
不,如果没有读到整个文件到达那一点就不可能到达3412行(除非你的行都有固定的大小)。
答案 1 :(得分:1)
这是一个可能的解决方案的开始:
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;
}
答案 2 :(得分:0)
只需先逐行阅读并计算行号,然后在您提到的行位置开始获取所需的内容。
答案 3 :(得分:0)
我建议使用RandomAccessFile,这个类使您可以跳转到文件中的特定位置。因此,如果您想要读取文件的最后一行,您不必阅读所有前面的行,您可以跳转到该行。