使用intelliJ在Java中创建txt文件会产生错误

时间:2019-04-30 09:47:59

标签: java ubuntu intellij-idea

我在IntelliJ中创建了一个新项目,并使用以下代码创建了一个新类:

import java.io.PrintWriter;

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

我希望这会在工作目录中创建一个txtfile,其中包含“只需编写一些文本以打印到您的文件”。但是,它只是返回了错误:

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

1 个答案:

答案 0 :(得分:0)

应该是这样(使用try / catch):

try {
       PrintWriter writeMe = new PrintWriter(new File("newFIle.txt"));
       writeMe.println("Just writing some text to print to your file ");
       writeMe.close();
} catch (FileNotFoundException e) {e.printStackTrace();}