gpt4 book ai didi

java - 使用多线程从多个文件读取并将它们写入文件文件序列

转载 作者:太空宇宙 更新时间:2023-11-04 06:29:24 24 4
gpt4 key购买 nike

我想使用多线程读取多个文件并将它们写入单个文件。我已经完成了一些代码,可以很好地读取文件内容并将它们写入另一个文件。但我的问题是数据不是连续的。就像读取f1并写入输出文件,然后读取f2并写入输出文件等等。看看我的代码

public MultiFileReadingThread(BufferedWriter writer, BufferedReader reader, String name, java.util.List<File> files){
this.writer = writer;
this.reader = reader;
this.name = name;
this.files = files;
}

@Override
public void run() {
SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss:ms");
System.out.println("Start Time : " + name + formatter.format(System.currentTimeMillis()));
// readFile();
if(i == 1){

}
writeIntoSharedBufferedWriter();
System.out.println("End Time : " + name + formatter.format(System.currentTimeMillis()));
}

public void writeIntoBufferedWriter(){

for(File f : files){
try{
BufferedReader r = new BufferedReader(new FileReader(f));
String line = null;
while((line = r.readLine()) != null){
writer.write(line);
writer.write("\n");
}
} catch(Exception ex){
ex.printStackTrace();
}
}
}

运行线程的代码。他们有五个不同的任务和工作人员。这段代码再次给出了我的结果,但不正确。如 f1、f2、f3

BufferedReader r1 = new BufferedReader(new FileReader(new File("/home/naveen/f1")));
BufferedReader r2 = new BufferedReader(new FileReader(new File("/home/naveen/f2")));
BufferedReader r3 = new BufferedReader(new FileReader(new File("/home/naveen/f3")));
BufferedReader r4 = new BufferedReader(new FileReader(new File("/home/naveen/f4")));
BufferedReader r5 = new BufferedReader(new FileReader(new File("/home/naveen/f5")));

BufferedWriter writer = new BufferedWriter(new FileWriter(new File("/home/naveen/write")));
Runnable task1 = new MultiFileReadingThread(null, writer, r1, "f");
Runnable task2 = new MultiFileReadingThread(null, writer, r2, "s");
Runnable task3 = new MultiFileReadingThread(null, writer, r3, "t");
Runnable task4 = new MultiFileReadingThread(null, writer, r4, "fu");
Runnable task5 = new MultiFileReadingThread(null, writer, r5, "fi");

Thread wroker1 = new Thread(task1, "w1");
Thread wroker2 = new Thread(task2, "w2");
Thread wroker3 = new Thread(task3, "w3");
Thread wroker4 = new Thread(task4, "w4");
Thread wroker5 = new Thread(task5, "w5");

有人可以帮助实现这些任务吗?提前致谢。

最佳答案

更好的方法是使用生产者消费者模式。生产者线程将读取文件并将内容包装在某个类中将其发送给消费者。这会将组合文件写入磁盘。

在消费者端,您可以使用优先级队列并让生产者设置优先级。

关于java - 使用多线程从多个文件读取并将它们写入文件文件序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26346424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com