This program is run when there is no extant file named "Test Object.to". The output of this program is "IO caught". 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. If you print the error, you see:
java.io.NotSerializableException: TestObject
Again, as per the docs , writeObject
requires that its argument be Serializable
. Since Serializable
is just a marker interface, you can just implement it:
class TestObject implements Serializable
and now your code doesn't throw any errors.
好的,我现在看到 TestObject 显然需要实现 Serializable
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.