【发布时间】:2014-10-18 11:28:27
【问题描述】:
嗨,我正在学习对象序列化并尝试了这个
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^SS§±éØ^B^@^BI^@^BidL^@^Dnamet^@^RLjava/lang/String;xp^ @^@^@^Nt^@^GSainath
~
我似乎无法理解我哪里出错了,请帮忙!
【问题讨论】:
-
您应该了解什么是变量范围。还要检查 try-with-resources。
-
哦! , try {//object declaration} 中的对象是否限制在 try 块内?
-
您是 99% 正确的,因为受限于范围的不是对象,而是变量(引用)。因此,如果您想在
try之外使用它(如在catch或finally中),则需要在try块之前创建引用。您可以将此引用设置为null,并在try中更改其值。您可以使用 try-with-resources 让编译器自动处理它 -
好的! ,我明白了,感谢您的明确回答,我还检查了 try with ,这似乎是对 Java SE:7 的一个非常有用的补充,.
标签: java exception-handling java-io object-serialization cannot-find-symbol