Read two text files at the same time – Java
•
Java
I have text files in two different languages, which are aligned line by line That is, the first line in textfile1 should be equal to the first line in textfile2, and so on
Is there any way to read these two files line by line at the same time?
The following is an example of how files should be displayed, assuming that the number of lines per file is approximately 1000000
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:
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
Expected output
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
At present, I can use it, but saving millions in 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++; }
Solution
Place the call nextline on two readers in the same loop:
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); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码