【发布时间】: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。 -
我之前关于删除循环的问题的原因与文件刷新有关。