创建新的FileOutputStream时出现FileNotFoundException

时间:2016-05-28 07:02:25

标签: java

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.setOut(new PrintStream (new FileOutputStream("out.txt", false)));
    while(sc.hasNext()) System.out.println(sc.nextInt());

}

我已经尝试了上面的代码并得到了这个

Error:(9, 40) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

我使用IntelliJ IDEA社区,有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

public static void main(String[] args) throws IOException{
    Scanner sc = new Scanner(System.in);
    System.setOut(new PrintStream (new FileOutputStream("out.txt", false)));
    while(sc.hasNext()) System.out.println(sc.nextInt());
}

你需要在方法声明中抛出它,或者你可以使用try catch block

public static void main(String[] args) throws IOException{
    Scanner sc = new Scanner(System.in);
    try {
        System.setOut(new PrintStream (new FileOutputStream("out.txt", false)));
    } catch(IOException e) {
        e.printstacktrace();
    }
    while(sc.hasNext())
        System.out.println(sc.nextInt());
}