错误:未报告的exceptionFileNotFoundException; 必须被抓住或宣布被抛出

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

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-grip向我抛出以下错误:

  ----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很新,我不知道这意味着什么。 任何人都能指出我正确的方向吗?

您没有告诉编译器有可能抛出FileNotFoundException如果文件不存在,将抛出FileNotFoundException

试试这个

 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 } } 

如果文件有问题, PrintWriter可能会抛出exception,就好像文件不存在一样。 所以你必须添加

 public static void main(String[] args) throws FileNotFoundException { 

然后它将编译并使用try..catch子句来捕获和处理exception。

如果你是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(); } } 

这意味着当您调用new PrintWriter(file) ,它可能会抛出exception。 您需要处理该exception,或者让您的程序能够重新抛出它。

 import java.io.*; public class Testing { public static void main(String[] args) { File file = new File ("file.txt"); file.getParentFile().mkdirs(); PrintWriter printWriter; try { printwriter = new PrintWriter(file); printWriter.println ("hello"); printWriter.close(); } catch (FileNotFoundException fnfe) { // Do something useful with that error // For example: System.out.println(fnfe); } }