简体   繁体   中英

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

PrintWriter works (it writes to the external file) until I add the line that says Thread.sleep(100); . Then the code still compiles just fine, and it continues writing to the console, but it won't print to the external file. But I can't figure out why?

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

The difference sleep makes in your case is that it slows down frequency of writes and and it will take a while until the writes get flushed into the file. By removing the sleep you are causing the write flush to happen much more earlier. Change the sleep time into something smaller (like 5 instead of 100) or wait a little longer and see that the file gets written over.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM