为什么 PrintWriter 不能与 Thread.sleep() 一起使用

Why doesn't PrintWriter work with Thread.sleep()

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();
        }
    }
  }
}

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