【问题标题】:Why doesn't PrintWriter work with Thread.sleep()为什么 PrintWriter 不能与 Thread.sleep() 一起使用
【发布时间】:2019-04-11 09:28:16
【问题描述】:

PrintWriter 工作(它写入外部文件),直到我添加说Thread.sleep(100); 的行。然后代码仍然编译得很好,它继续写入控制台,但不会打印到外部文件。但我不知道为什么?

import java.io.*; 
import java.io.PrintWriter;
import java.io.File;
import javax.swing.*;

public class RecordMouse {
  public static void main(String[] args) throws InterruptedException{

    String line = "";

    // string for filename
    String filename = System.currentTimeMillis() + "out.txt";
    // create file
    File file = new File(filename);
    // create writer
    PrintWriter printWriter = null;

    try
    {
        printWriter = new PrintWriter(file);

        while(true){
            //Thread.sleep(100);
            System.out.println(System.currentTimeMillis() + " hi \n");
            printWriter.println(System.currentTimeMillis() + " hi");
        }

    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    finally
    {
        if ( printWriter != null ) 
        {
            printWriter.close();
        }
    }
  }
}

【问题讨论】:

  • 它工作时有什么作用?不工作的时候怎么办?
  • 什么不完全有效? Thread.sleep() 抛出 InterruptedException,并且您的代码没有捕获该类型的异常。
  • 在标题中。我会在帖子中详细说明。
  • @Mike 我不明白为什么这应该是个问题。 main 方法声明它抛出 InterruptedException
  • 我之前关于删除循环的问题的原因与文件刷新有关。

标签: java sleep


【解决方案1】:

sleep 在您的情况下的不同之处在于它降低了写入频率,并且需要一段时间才能将写入刷新到文件中。通过删除sleep,您将导致写入刷新发生得更早。将睡眠时间更改为更小的值(例如 5 而不是 100)或稍等片刻,然后查看文件是否被写入。

【讨论】:

  • 或者为每个循环迭代添加一个刷新调用。
  • 谢谢。我不明白的问题是流和缓冲区之间的区别。或者缓冲区最终会转储。更改睡眠时间是不可取的,因为我不想要那么多数据,但我能够将 printWriter.flush(); 添加到循环中,因为 @StephenC 建议将缓冲的数据刷新到文件中。
猜你喜欢
  • 2012-03-20
  • 2015-09-25
  • 2018-03-09
  • 2021-06-14
  • 2012-10-09
  • 2020-03-18
  • 2017-11-21
  • 2012-09-19
  • 2013-12-30
相关资源
最近更新 更多