简体   繁体   English

为什么会抛出 IOException

[英]Why Does It Throw an IOException

This program is run when there is no extant file named "Test Object.to".该程序在没有名为“Test Object.to”的现存文件时运行。 The output of this program is "IO caught".该程序的输出是“IO 捕获”。 Why?为什么?

import java.io.*;

public class Test 
{
    public static void main (String [] args)
    {
        TestObject testObject = new TestObject("Test Object");
        
        try
        {
            saveTestObject(testObject);
        }
        catch (FileNotFoundException fnf)
        {
            System.out.println("FNF caught");
        }
        catch (IOException io)
        {
            System.out.println("IO caught");
        }
    }
    
    static void saveTestObject(TestObject to)  throws FileNotFoundException, IOException
    {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(to.name + ".to"));
        oos.writeObject(to);
        oos.close();
    }
}

class TestObject
{
    String name;
    
    TestObject(String s)
    {
        name = s;
    }
}

First of all, this does not throw a FileNotFoundException , since as per the docs , FileOutputStream 's constructor will create the file if it doesn't exist instead of throwing an error.首先,这不会抛出FileNotFoundException ,因为根据 docsFileOutputStream的构造函数将在文件不存在时创建该文件,而不是抛出错误。 If you print the error, you see:如果打印错误,您会看到:

java.io.NotSerializableException: TestObject

Again, as per the docs , writeObject requires that its argument be Serializable .同样, 根据 docswriteObject要求其参数是Serializable Since Serializable is just a marker interface, you can just implement it:由于Serializable只是一个标记接口,你可以实现它:

class TestObject implements Serializable

and now your code doesn't throw any errors.现在您的代码不会抛出任何错误。

好的,我现在看到 TestObject 显然需要实现 Serializable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM