【问题标题】:FileOutputStream file not found errorFileOutputStream 文件未找到错误
【发布时间】:2009-04-08 09:47:35
【问题描述】:

以下代码有问题。我正在尝试写入 .ppm 文件,但我得到了

Red.java:6:未报告的异常 java.io.FileNotFoundException;必须被抓住或宣布被抛出 FileOutputStream fout = new FileOutputStream(fileName); ^ 有什么想法吗?

导入 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();
}

}

【问题讨论】:

  • 顺便说一下,我的代码在上面正确显示。将不胜感激有关如何使代码部分从适当位置开始的提示。
  • 我可以指出(不相关)您正在为您的文件名打开一个新流,但写入标准输出(通过 System.out)。因此,您的 .ppm 内容将转到控制台而不是文件。
  • 谢谢,我认为这是个问题。我是从一个有缺陷的例子开始的。

标签: java file-io


【解决方案1】:

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

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

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

事实上,您可能想要在上面的main() throws 子句中声明IOException。您调用的不同方法将被声明为 this 的 throwing 变体。

【讨论】:

    【解决方案2】:

    FileNotFoundException 是一个检查异常。您需要将尝试写入文件的代码包含在 try/catch 块中,或者抛出异常。

    【讨论】:

    • "或抛出异常"。将异常声明为抛出,确定吗?
    【解决方案3】:

    您是否在记事本中编写代码?尝试使用 Eclipse。它会在有未捕获异常问题的代码下划线,然后您只需将光标放在带下划线的部分(给出错误的行),按Ctrl+1 获取解决方案列表,然后在列表中选择一个。我想用try{}catch{} 包围这个块会平息异常,除非你 - 想 - 对此做点什么。

    【讨论】:

    • 如果您的作业只是关闭错误消息,则将所有代码放在 tr { } 块中,最后键入 catch (Exception e) {}。这会掩盖任何事情。尽管以后永远不要这样做,并阅读有关 Java 异常处理的一章。
    【解决方案4】:

    FileNotFoundException 未在代码中处理。添加 FileOutputStream fout = new FileOutputStream(fileName);在 try catch 块之间可以解决问题。

    import java.io.*;
    public class Red {
        public static void main(String args[]) {
    
        String fileName = "RedDot.ppm"; 
        try
        {
            FileOutputStream fout = new FileOutputStream(fileName);
            DataOutputStream out = new DataOutputStream(fout);
        }catch(FileNotFoundException fnfExcep){
            System.out.println("Exception Occurred " + fnfExcep.getMessage() );
        }
        System.out.print("P6 1 1 255 ");
            System.out.write(255);
            System.out.write(0);
            System.out.write(0);
            System.out.flush();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 2016-06-05
      • 2018-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多