错误: 未报告的异常 FileNotFoundException;必须被捕获或声明被抛出

2022-09-03 14:05:26

我正在尝试创建一个简单的程序,将字符串输出到文本文件。使用我在这里找到的代码,我将以下代码放在一起:

import java.io.*;

public class Testing {

  public static void main(String[] args) {

    File file = new File ("file.txt");
    file.getParentFile().mkdirs();

    PrintWriter printWriter = new PrintWriter(file);
    printWriter.println ("hello");
    printWriter.close();       
  }
} 

J-grasp给我带来了以下错误:

 ----jGRASP exec: javac -g Testing.java

Testing.java:10: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
    PrintWriter printWriter = new PrintWriter(file);
                              ^
1 error

 ----jGRASP wedge2: exit code for process is 1.

由于我是Java的新手,我不知道这意味着什么。任何人都可以给我指出正确的方向吗?


答案 1

您不是在告诉编译器,如果文件不存在,则有机会抛出 a will。FileNotFoundExceptionFileNotFoundException

试试这个

public static void main(String[] args) throws FileNotFoundException {
    File file = new File ("file.txt");
    file.getParentFile().mkdirs();
    try
    {
        PrintWriter printWriter = new PrintWriter(file);
        printWriter.println ("hello");
        printWriter.close();       
    }
    catch (FileNotFoundException ex)  
    {
        // insert code to run when exception occurs
    }
}

答案 2

如果你对Java很陌生,只是想学习如何使用,这里有一些基本的代码:PrintWriter

import java.io.*;

public class SimpleFile {
    public static void main (String[] args) throws IOException {
        PrintWriter writeMe = new PrintWriter("newFIle.txt");
        writeMe.println("Just writing some text to print to your file ");
        writeMe.close();
    }
}

推荐