[英]Why doesn't PrintWriter work with Thread.sleep()
直到我添加說Thread.sleep(100);
的行,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),或者稍等一會兒,看文件是否被覆蓋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.