java - FileOutputStream 文件未找到错误

标签 java file-io

我在使用以下代码时遇到问题。我正在尝试写入 .ppm 文件,并且得到

Red.java:6: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown FileOutputStream fout = new FileOutputStream(fileName); ^ Any ideas?

导入java.io.*;

公开课红色{

public static void main(String args[]) {

String fileName = "RedDot.ppm"; 
FileOutputStream fout = new FileOutputStream(fileName); 
DataOutputStream out = new DataOutputStream(fout);

System.out.print("P6 1 1 255 ");
    System.out.write(255);
    System.out.write(0);
    System.out.write(0);
    System.out.flush();
}

}

最佳答案

最简单的解决方案是重写您的主要声明:

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

这表明如果它无法创建输出流(无论出于何种原因),它可能抛出此异常。请注意,在这种情况下,FileNotFoundException 不是异常的最佳名称,但这是一个您无法处理的命名问题。

事实上,您可能希望在上面的 main() throws 子句中声明 IOException。您调用的不同方法将被声明为该方法的抛出变体。

关于java - FileOutputStream 文件未找到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/729283/

相关文章:

python - 读取同一行中多个项目的项目

java - 这个 while 循环的时间复杂度

java - 实现 try/catch block

java - Java 中的相对文件引用

c++ - fwrite 比 Windows 中的 WriteFile 快吗?

c# - WinRT 记录到文件

python - 在 python 中将 namedtuple 写入和读取文件

java - 解析 Android/Java SoapObject 返回数据的最佳方法

java - 如何访问列表中对象的方法

Java 8 谓词