2011-10-30 1 views
0

私は、serialastionを使ってバイナリファイルにarrayListを保存しました。このデータをバイナリファイルからどのように取得するのですか?で宣言された配列リストJavaのバイナリファイルからデータのArrayListをどのように逆シリアル化するのですか?

public void readInSerialisable() throws IOException 
{ 
    FileInputStream fileIn = new FileInputStream("theBKup.ser"); 

    ObjectInputStream in = new ObjectInputStream(fileIn); 

    try 
    { 
    ArrayList readob = (ArrayList)oi.readObject(); 
       allDeps = (ArrayList) in.readObject(); 
    } 
    catch (IOException exc) 
    { 
     System.out.println("didnt work"); 
    } 
} 

allDepsさ:

この

は私がシリアライズ

public void createSerialisable() throws IOException 
{ 
    FileOutputStream fileOut = new FileOutputStream("theBkup.ser"); 
    ObjectOutputStream out = new ObjectOutputStream(fileOut); 
    out.writeObject(allDeps); 
    options(); 
} 

のために使用しているコードと私はArrayListのの直列化復元のために使用しようとしています。このコードでありますクラスコンストラクタ。私はこのクラスで宣言されたarrayListにファイルからarrayListを保存しようとしています。

+0

それは何のarraylistですか? –

+0

名前と所在地を持つ部署 – Binyomin

+0

そして 'oi'とは何ですか? –

答えて

1

あなたのコードはほとんど正しいですが、間違いが1つあり、それがうまくいくかもしれません。アスタリスクで強調表示しています(明らかに、私は「コード」モードで太字にすることはできません)。

public void createSerialisable() throws IOException 
{ 
    FileOutputStream fileOut = new FileOutputStream("theBkup.ser"); 
    ObjectOutputStream out = new ObjectOutputStream(fileOut); 
    out.writeObject(allDeps); 
    **out.flush();** // Probably not strictly necessary, but a good idea nonetheless 
    **out.close();** // Probably not strictly necessary, but a good idea nonetheless 
    options(); 
} 

public void readInSerialisable() throws IOException 
{ 
    FileInputStream fileIn = new FileInputStream("theBKup.ser"); 

    ObjectInputStream in = new ObjectInputStream(fileIn); 

    try 
    { 
     **// You only wrote one object, so only try to read one object back.** 
     allDeps = (ArrayList) in.readObject(); 
    } 
    catch (IOException exc) 
    { 
     System.out.println("didnt work"); 
     **exc.printStackTrace();** // Very useful for findout out exactly what went wrong. 
    } 
} 

希望します。それでも問題が発生した場合は、スタックトレースと問題を示すコンパイル可能な完全な例を投稿するようにしてください。

allDepsには実際にSerializableというオブジェクトが含まれており、問題はcreateSerialisableではなくreadInSerialisableであることに注意してください。ここでも、スタックトレースは非常に役立ちます。

+0

ありがとうキャメロンがたくさんありますが、 それはまだコンパイルされません "その報告されていない例外ClassNotFoundはキャッチする必要がありますまたは投げられると宣言する必要があります" オンライン:allDeps1 =(ArrayList)in.readObject(); – Binyomin

+0

ああ*コンパイルエラーであるとは言いませんでした。簡単です: 'try'ブロックの後に' catch(ClassNotFoundException e) 'ブロックを追加してください。あるいは単に 'catch(IOException exc)'を 'catch(Exception exc)'に変更してください。 –

+0

あなたの助けをありがとう、すべて今良い:) – Binyomin

関連する問題