我需要使用Java逐行读取大约5-6 GB的大型文本文件。

我怎样才能快速做到呢?


当前回答

在Java 8中,除了使用Files.lines(),还有另一种方法。如果您的输入源不是文件,而是更抽象的东西,如Reader或InputStream,则可以通过BufferedReaders lines()方法对行进行流处理。

例如:

try (BufferedReader reader = new BufferedReader(...)) {
  reader.lines().forEach(line -> processLine(line));
}

BufferedReader读取的每个输入行都会调用processLine()。

其他回答

你所能做的就是使用扫描仪扫描整个文本,并逐行浏览文本。 当然,您应该导入以下内容:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public static void readText throws FileNotFoundException {
    Scanner scan = new Scanner(new File("samplefilename.txt"));
    while(scan.hasNextLine()){
        String line = scan.nextLine();
        //Here you can manipulate the string the way you want
    }
}

扫描仪基本上扫描所有的文本。while循环用于遍历整个文本。

hasnextline()函数是一个布尔值,如果文本中还有更多行,则返回true。. nextline()函数将整行作为字符串提供给你,然后你可以使用你想要的方式。尝试System.out.println(line)来打印文本。

旁注:.txt是文件类型文本。

你可以使用Scanner类

Scanner sc=new Scanner(file);
sc.nextLine();

看看这个博客:

Java逐行读取文件- Java教程

可以指定缓冲区大小或 可以使用默认大小。的 违约对大多数人来说已经足够大了 目的。

// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

String strLine;

//Read File Line By Line
while ((strLine = br.readLine()) != null)   {
  // Print the content on the console
  System.out.println (strLine);
}

//Close the input stream
fstream.close();

你可以使用下面的代码:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadTextFile {

    public static void main(String[] args) throws IOException {

        try {

            File f = new File("src/com/data.txt");

            BufferedReader b = new BufferedReader(new FileReader(f));

            String readLine = "";

            System.out.println("Reading file using Buffered Reader");

            while ((readLine = b.readLine()) != null) {
                System.out.println(readLine);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

对于使用Kotlin的Android开发者来说:

val myFileUrl = object{}.javaClass.getResource("/vegetables.txt")
val file = File(myFileUrl.toURI())
file
    .bufferedReader()
    .lineSequence()
    .forEach(::println)

Or:

val myFileUrl = object{}.javaClass.getResource("/vegetables.txt")
val file = File(myFileUrl.toURI())
file.useLines { lines ->
    lines.forEach(::println)
}

注:

txt文件应该在您的类路径中(例如,在src/main/resources目录中) 上述解决方案都默认将文件编码处理为UTF-8。您可以指定所需的编码作为函数的参数。 上述解决方案不需要任何进一步的操作,如关闭文件或读取器。它们由Kotlin标准库自动处理。