【发布时间】: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 > englishandfrench -
我必须存储它们,并且很可能在从两个文件中读取每个句子后立即将它们索引到文本文件中。
标签: java io text-files readfile