【问题标题】:Creating a txt file in java with intelliJ creates error使用 intelliJ 在 java 中创建 txt 文件会产生错误
【发布时间】:2019-04-30 09:47:59
【问题描述】:

我在 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

【问题讨论】:

  • 必须捕获列出的异常类型(添加try/catch 块)或声明抛出(添加throws FileNotFoundException 到您的方法声明)。
  • 一遍又一遍地阅读错误,直到你知道它的含义......我的意思是来吧......
  • 我对 java 很陌生,我知道如何尝试/捕获,但什么是“抛出 FileNotFoundException”,如果我希望代码正常工作,为什么我需要捕获异常?
  • FileNotFoundException 是一个检查异常。这意味着编译器会检查您的代码,以确保您将在任何可能发生的情况下处理异常(或至少声明它可能发生)。

标签: java ubuntu intellij-idea


【解决方案1】:

应该是这样的(使用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();}

【讨论】:

  • 我收到错误:错误:(10、18)java:找不到符号符号:类 FileNotFoundException 位置:类 myWriter
  • import java.io.FileNotFoundException;
猜你喜欢
  • 2011-03-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 2019-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-24
相关资源
最近更新 更多