簡體   English   中英

Java對象序列化,無法關閉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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM