BufferedWriter不生成输出到File

时间:2014-10-25 08:24:58

标签: java file output bufferedwriter

在我的代码中,我必须从第二个单词开始,然后反转它。其他类/线程正在完成他们的工作。我可以将输出打印到控制台窗口并正确打印。但是,每当我尝试写入我桌面上的文本文件时,它都不会产生任何输出。

我的代码:

package ProducerConsumerAssignment;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import java.util.concurrent.BlockingQueue;

/**
 *
 * @author Tyler Weaver
 */
public class WordWriter implements Runnable {

    private final String END_FLAG = "Terminate the queue";
    private static BlockingQueue<CharSequence> in;
    private final File output;

    /**
     * Constructs a WordWriter object
     *
     * @param file the file to write words to
     * @param queue the blocking queue to retrieve words from
     */
    public WordWriter(final File file, BlockingQueue queue) {
        output = file;
        in = queue;
    }

    /**
     * Executes when being called in a thread
     */
    @Override
    public void run() {
        boolean isInterrupted = false;

        while (!isInterrupted) {
            try (BufferedWriter out = new BufferedWriter(new FileWriter(output))) {
                CharSequence word = in.take();

                if (word.toString().equalsIgnoreCase(END_FLAG))
                    Thread.currentThread().interrupt();

                out.write(word.toString() + " ");
                System.out.printf("%s%n", word);
            } catch (IOException ex) {
                System.err.printf("Error closing the file!%n%s%n", ex);
            } catch (InterruptedException ex) {
                isInterrupted = true;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您正在每次迭代时关闭BufferedWriter

您可以将BufferedWriter对象移出while循环,并在结尾处调用BufferedWriter.close()

BufferedWriter writer = new BufferedWriter(new FileWriter(String));
while (true) {
    CharSequence word = in.take();
    if (word.toString().equalsIgnoreCase(END_FLAG)) {
        break;
    }
    try {
        writer.write(word + " ");
    } catch (IOException io) {
        break;
    }
}
writer.close();