【问题标题】:Read two textfile line by line simultaneously -java同时逐行读取两个文本文件-java
【发布时间】:2012-05-31 09:35:34
【问题描述】:

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

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

下面是文件的外观示例,假设每个文件的行数约为 1,000,000。

文本文件1:

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

文本文件2:

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 中保存几百万行会杀死我的机器。

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++;
}

【问题讨论】:

  • 为什么不将两个读取合并到一个while循环中?
  • 我想说,给定两个 1,000,000 行文件,它们都完全对齐所有 1,000,000 行的可能性非常小。除非你能解决这个问题,否则你的代码会很脆弱。
  • 您必须只打印这些行还是必须存储它们?
  • 也许有一天它会对你有用,但是,如果你在 Unix 系统上工作,请考虑使用这个命令:paste -d '\t' english french &gt; englishandfrench
  • 我必须存储它们,并且很可能在从两个文件中读取每个句子后立即将它们索引到文本文件中。

标签: java io text-files readfile


【解决方案1】:

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);
}

【讨论】:

  • 谢谢它现在可以工作了,我认为index 将有助于计算句子的数量。但我使用if(...)continue; 而不是break;
【解决方案2】:

我会这样做:

List<String> strings = new ArrayList<String>();
BufferedReader enBr = ...
BufferedReader frBr = ...

String english = "";
String french = "";
while (((english = enBr.readline()) != null) && ((french = frBr.readline) != null))
{
    strings.add(english + "\t" + french);
}

【讨论】:

  • 但如果法语文件包含更多行,这些行将不会成为结果的一部分。
  • @Zakaria:如果这是真的,那么我认为这个说法不成立: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.
  • =) 这个方法也可以,但是没有全局的String englishString french,另一种方法更直观。如果我必须与前一个句子进行比较以查看它是否相同,此解决方案将更贴切。
  • @npinti :恕我直言,“应该”部分必须通过处理不合格文件来实现(例如:不同的行数):)
  • 如果有多个文件怎么办?
猜你喜欢
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-14
  • 1970-01-01
  • 2017-10-01
  • 1970-01-01
相关资源
最近更新 更多