同时读取两个文本文件-java [英] Read two textfile line by line simultaneously -java

查看:522
本文介绍了同时读取两个文本文件-java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种不同语言的文本文件,它们是逐行对齐的。即textfile1中的第一行应该等于textfile2中的第一行,依此类推。

I have 2 textfiles in two different languages and they are aligned line by line. I.e. the first line in the textfile1 should be equals to the first line in textfile2, and so on and so forth.

有没有办法逐行读取这两个文件同时排队?

Is there a way to read both file line-by-line simultaneously?

下面是文件应该如何显示的示例,假设每个文件的行数大约为1,000,000。

Below is a sample of how the files should look like, imagine the number of lines per file is around 1,000,000.

textfile1:

textfile1:

This is a the first line in English
This is a the 2nd line in English
This is a the third line in English

textfile2:

textfile2:

C'est la première ligne en Français
C'est la deuxième ligne en Français
C'est la troisième ligne en Français

期望的输出

This is a the first line in English\tC'est la première ligne en Français
This is a the 2nd line in English\tC'est la deuxième ligne en Français
This is a the third line in English\tC'est la troisième ligne en Français

目前,我可以使用它,但在RAM中保存几百万行会导致我的机器死机。

Currently, i can use this but saving a few million lines in the RAM will kill my machine.

String english = "/home/path-to-file/english";
String french = "/home/path-to-file/french";
BufferedReader enBr = new BufferedReader(new FileReader(english));
BufferedReader frBr = new BufferedReader(new FileReader(french));

ArrayList<String> enFile = new ArrayList<String>();
while ((line = enBr.readLine()) != null) {
    enFile.add(line);
}

int index = 0;
while ((line = frBr.readLine()) != null) {
    String enSentence = enFile.get(index);
    System.out.println(line + "\t" + enSentence);
    index++;
}


推荐答案

拨打电话<$同一循环中两个读者的c $ c> nextLine :

String english = "/home/path-to-file/english";
String french = "/home/path-to-file/french";
BufferedReader enBr = new BufferedReader(new FileReader(english));
BufferedReader frBr = new BufferedReader(new FileReader(french));

while (true) {
    String partOne = enBr.readLine();
    String partTwo = frBr.readLine();

    if (partOne == null || partTwo == null)
        break;

    System.out.println(partOne + "\t" + partTwo);
}

这篇关于同时读取两个文本文件-java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆