简体   繁体   English

创建新的FileOutputStream时出现FileNotFoundException

[英]FileNotFoundException when create new FileOutputStream

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());

}

I've tried the above code and got this 我已经尝试了上面的代码并得到了

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

I'm using IntelliJ IDEA Community, anyone know how to solve this? 我正在使用IntelliJ IDEA社区,有人知道如何解决这个问题吗?

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());
}

you need to throw it at the method declaration or you can use try catch block 您需要将其扔到方法声明中,也可以使用try catch块

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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM