![](/img/trans.png)
[英]Java object serialization, how to use same file after using it with ObjectOutPutStream
[英]Java Object Serialization ,Unable to close ObjectOutputStream?
嗨,我正在学习对象序列化并试过这个
import java.io.*;
class Employee implements Serializable{
Employee(int temp_id,String temp_name)
{
id=temp_id;
name=temp_name;
}
int id;
String name;
}
public class SerialTest{
public static void main(String[] args)
{
Employee e1=new Employee(14,"John");
try{
FileOutputStream fileStream=new FileOutputStream("myserial.ser");
ObjectOutputStream os=new ObjectOutputStream(fileStream);
os.writeObject(e1);
}
catch(IOException ioex)
{
ioex.printStackTrace();
}
finally{
os.close();
}
}//main ends
}//class ends
在我打电话之前,这个程序工作正常
os.close();
现在我没有编译,我得到错误说
SerialTest.java:29: cannot find symbol
symbol : variable os
location: class SerialTest
os.close();
^
它在我尝试关闭ObjectOutPutStream之前工作,序列化文件的内容如下,
¬í^ @ ^ ESR ^ @ ^ HEmployee 2 -S <89>S§±<9B> EO ^ B ^ @ ^ BI ^ @ ^ BidL ^ @ ^ Dnamet ^ @ ^ RLjava /郎/字符串; XP ^ @ ^ @ ^ @ ^ Nt ^ @ ^ GSainath~
我似乎无法理解我哪里出错了,请帮忙!
您想要使用专用的try-with-resources :
try (ObjectOutputStream os =
new ObjectOutputStream(new FileOutputStream("myserial.ser"));) {
os.writeObject(e1);
} catch(IOException ioex) {
ioex.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.