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

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?

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

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

desired 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

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 enFile = new ArrayList();

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

}

解决方案

Put the calls to nextLine on both 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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值