在java中使用Thread来读写文件

时间:2012-06-04 06:11:32

标签: java multithreading

我想制作一个逐行读取文件的程序,然后将这些行写入另一个文件。我想使用两个单独的线程来解决这个问题。第一个Thread读取一行,然后将其传递给另一个Thread,后者负责通过消息将该行写入另一个文件。应该重复此过程,直到达到文件结尾。

我该怎么做?

1 个答案:

答案 0 :(得分:4)

你想要的是producer-consumer model。使用两个Thread个对象和一个ArrayBlockingQueue实现起来并不是很难。这是一些启动代码:

// we'll store lines of text here, a maximum of 100 at a time
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(100);

// code of thread 1 (producer)
public void run() {
   while(/* lines still exist in input file */) {
       String line = // read a line of text
       queue.put(line); // will block if 100 lines are already inserted
   }
   // insert a termination token in the queue
}

// code of thread 2 (consumer)
public void run() {
   while(true) {
       String line = queue.take(); // waits if there are no items in the queue
       if(/* line is termination token */) break;
       // write line to file
   }   
}

希望这会有所帮助。我不能给出完整的代码,如果你试图填补空白,那就更好了。