我对 Java 中的 PrintWriter 有疑问,这是我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Out {
public static void main(String[] args) {
try{
File a=new File("C:/Users/Acer/Desktop/abc.txt");
PrintWriter out=new PrintWriter(a);
Scanner c=new Scanner(System.in);
while(c.hasNextInt()){
out.printf("%d", c.nextInt());
out.println();
c.close();
}
out.close();
System.out.println("input written into file successfully!");
}
catch(FileNotFoundException e){
System.out.println("The file not found");
}
}
}
运行程序后,文件 abc 的内容丢失了,然后我执行 Scanner 功能输入 1 2 3 4 5,它显示错误:
1 2 3 4 5
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Unknown Source)
at java.util.Scanner.hasNext(Unknown Source)
at java.util.Scanner.hasNextInt(Unknown Source)
at java.util.Scanner.hasNextInt(Unknown Source)
at Out.main(Out.java:17)
它应该输出:
1
2
3
4
5
但是程序似乎找不到文件,我不确定哪个部分是错误的,请帮助,干杯!