同时读取两个文本文件-java

前端之家收集整理的这篇文章主要介绍了同时读取两个文本文件-java前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两种不同语言的文本文件,它们是逐行对齐的.即textfile1中的第一行应该等于textfile2中的第一行,依此类推.

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

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

textfile1:

@H_301_8@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:

@H_301_8@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

期望的输出

@H_301_8@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中保存几百万行将杀死我的机器.

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

解决方法

@H_502_25@ 将调用nextLine放在同一循环中的两个读取器上: @H_301_8@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相关文章