逐行处理大型文本文件的最有效方法是什么

时间:2013-05-24 13:13:09

标签: java

我(想)我正在逐行处理文本文件,直到找到特定的标记;

(Psuedo Code)

Scanner scanner = new Scanner(new FileReader("myTextFile.txt");
while (scanner.hasNext() {
    boolean found = process(scanner.nextLine();
    if (found) return;
}

有些文件很庞大。这段代码是否实际上逐行扫描文件,或者Scanner或FileReader是否将整个文件读入内存,然后逐行通过内存缓冲区工作?

3 个答案:

答案 0 :(得分:3)

BufferedReader br = new BufferedReader(new FileReader(file));
String line;
boolean found = false;
while ((line = br.readLine()) != null) {
     if(line.equalsIgnoreCase("Your string"))
       found = true;
}

答案 1 :(得分:1)

您需要BufferedInputStream

public static void main(String[] args) {

        File file = new File("C:\\testing.txt");
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        DataInputStream dis = null;

        try {
            fis = new FileInputStream(file);

            bis = new BufferedInputStream(fis);
            dis = new DataInputStream(bis);

            while (dis.available() != 0) {
                System.out.println(dis.readLine());
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                bis.close();
                dis.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

source

答案 2 :(得分:0)

Path filePath = Paths.get("myTextFile.txt");
boolean found = false;
try (BufferedReader br = Files.newBufferedReader(filePath, CharSet.forName(<char-set-name>)){
   for (String line = br.readLine(); line != null; line = br.readLine()) {
     found = process(line);
     if (found){
        break;
     };
   }
}