PrintWriter混乱

时间:2013-09-24 12:21:54

标签: java

我对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的内容丢失,然后我执行扫描程序功能键入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

但似乎该程序无法找到该文件,我不确定哪个部分是错误的,请帮忙,干杯!

3 个答案:

答案 0 :(得分:2)

您在已关闭的hasNextInt()对象Scanner上调用了c方法,该方法为您提供了执行权限。

所以c.close();应该在while循环

之外

答案 1 :(得分:1)

您正在关闭循环内部的Scanner对象!

尝试将它放在循环之外。

while(c.hasNextInt()){
    out.printf("%d", c.nextInt());
    out.println();
}
c.close();  

您的预期输出是:

input written into file successfully!

而不是:

1
2
3
4
5

答案 2 :(得分:0)

试试这个

while(c.hasNextInt()){
out.printf("%d", c.nextInt());
out.println();
}
 c.close();