【问题标题】:How to use PrintWriter and flush() to print something on a text file?如何使用 PrintWriter 和 flush() 在文本文件上打印内容?
【发布时间】:2012-06-11 19:28:10
【问题描述】:

我正在使用多线程来计算图像。每个线程计算一行,当一个线程已经在计算 line 时,下一个线程是否应该计算 one 之后的行。但我想确保每一行都只计算一次,为了做到这一点,我可以制作一个 System.out.println(CalculatedLineNumber) 并在文本文件中输出,这样当我用文本打开它时编辑器,我将直接查看打印的行数是否与文本文件上的行数相同。但是我该怎么做呢? 这是我完成计算的 run() 方法的代码片段:

public void run() {

                int myRow;
                while ( (myRow = getNextRow()) < getHeight() ) {
                    image.setRGB(0, myRow, getWidth(), 1, renderLine(myRow), 0, 0);
                }
            }

有人告诉我应该使用 PrintWriter 和 flush() 或类似的东西,但我不知道如何使用它.. 有人可以帮我吗? (“myRow”是我想写在文本文件上的行号,每个人都在不同的行)

非常感谢!!

【问题讨论】:

标签: java multithreading thread-safety printwriter


【解决方案1】:

我想确保每一行都只计算一次,

我建议您使用ExecutorService 并将每一行作为图像作业提交到线程池。请参阅底部的代码示例。如果你做对了,那么你就不必担心会有多少输出行。

我可以发System.out.println(CalculatedLineNumber)

我不太明白这样做的必要性。这是某种会计文件,可帮助您确保所有图像均已处理完毕?

有人告诉我应该使用 PrintWriter 和 flush()

您不需要flushPrintWriter,因为它已经在下面同步了。只需在每个作业结束时打印出结果,如果您将 X 行作业提交到 threadPool,那么您将有 X 行输出。

要使用PrintWriter,您只需:

PrintWriter printWriter = new PrintWriter(new File("/tmp/outputFile.txt"));
// each thread can do:
writer.println("Some sort of output: " + myRow);

这里有一些示例代码来展示如何使用ExecutorService 线程池。

PrintWriter outputWriter = ...;
// create a thread pool with 10 workers
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// i'm not sure exactly how to build the parameter for each of your rows
for (int myRow : rows) {
    // something like this, not sure what input you need to your jobs
    threadPool.submit(new ImageJob(outputWriter, myRow, getHeight(), getWidth()));
}
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();
...
public class ImageJob implements Runnable {
    private PrintWriter outputWriter;
    private int myRow;
    private int height;
    private int width;
    public MyJobProcessor(PrintWriter outputWriter, int myRow, int height,
            int width, ...) {
        this.outputWriter = outputWriter;
        this.myRow = myRow;
        this.height = height;
        this.width = width;
    }
    public void run() {
        image.setRGB(0, myRow, width, 1, renderLine(myRow), 0, 0);
        outputWriter.print(...);
    }
}

【讨论】:

  • 嗨,格雷,感谢您的出色回答。但我需要的想法要容易得多:它只是 while 循环中的 System.out.println(myRow)。但是我在控制台上会有太多的行,所以这个输出最好放在一个文本文件中。我应该怎么做,没有太多复杂的事情:-)谢谢!
  • 嗯。好的。我添加了PrintWriter 的用法。这是你需要的吗?
  • 是的,谢谢.. 但仍有一个问题:eclipse 告诉 PrintWriter printWriter = new PrintWriter(new File("outputFile.txt")); 的“Unhandled FileNotFoundException”。当我添加到“run()”时抛出 FileNotFoundExcpetion eclipse 告诉我要删除它.. 我该怎么办?
  • 天啊。您需要处理异常。见这里:docs.oracle.com/javase/tutorial/essential/exceptions
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多