2011-10-19 11 views
4

私は、クラスXYZの複数の直列化オブジェクトを含むファイルを持っています。シリアライズ中に、各XYZオブジェクトがファイルに追加されました。Javaのファイルからオブジェクトを逆シリアル化する

これで、ファイルから各オブジェクトを読み取る必要があり、最初のオブジェクトだけを読み取ることができました。

どのようにファイルから各オブジェクトを読み込み、最終的にそれをリストに格納することができますか?

+0

問題を説明するコードスニペットを入力してください。 – alf

+0

バイナリまたはXMLシリアル化? – spork

+0

オブジェクトはすべて単一のセッション(単一の 'ObjectOutputStream'インスタンス)で書かれていましたか、複数のセッション(作成、使用、それぞれに' ObjectOutputStream'を閉じる)がありましたか? –

答えて

9

次のことを試してみてください。

List<Object> results = new ArrayList<Object>(); 
    FileInputStream fis = new FileInputStream("cool_file.tmp"); 
    ObjectInputStream ois = new ObjectInputStream(fis); 

    try { 
     while (true) { 
      results.add(ois.readObject()); 
     } 
    } catch (OptionalDataException e) { 
     if (!e.eof) throw e; 
    } finally { 
     ois.close(); 
    } 

トムの華麗なコメントにフォローアップ、複数ObjectOutputStreamのためのソリューションは次のようになり、

public static final String FILENAME = "cool_file.tmp"; 

public static void main(String[] args) throws IOException, ClassNotFoundException { 
    String test = "This will work if the objects were written with a single ObjectOutputStream. " + 
      "If several ObjectOutputStreams were used to write to the same file in succession, " + 
      "it will not. – Tom Anderson 4 mins ago"; 

    FileOutputStream fos = null; 
    try { 
     fos = new FileOutputStream(FILENAME); 
     for (String s : test.split("\\s+")) { 
      ObjectOutputStream oos = new ObjectOutputStream(fos); 
      oos.writeObject(s); 
     } 
    } finally { 
     if (fos != null) 
      fos.close(); 
    } 

    List<Object> results = new ArrayList<Object>(); 

    FileInputStream fis = null; 
    try { 
     fis = new FileInputStream(FILENAME); 
     while (true) { 
      ObjectInputStream ois = new ObjectInputStream(fis); 
      results.add(ois.readObject()); 
     } 
    } catch (EOFException ignored) { 
     // as expected 
    } finally { 
     if (fis != null) 
      fis.close(); 
    } 
    System.out.println("results = " + results); 
} 
+0

results.add(ois.readObject());を呼び出します。 (ループ内) –

+4

オブジェクトが単一の 'ObjectOutputStream'で書き込まれている場合、これは動作します。いくつかの 'ObjectOutputStream'が同じファイルに連続して書き込むために使用された場合、それはされません。 –

+0

@RockyTritonよく見つかった:)はい、すでに修正されました、ありがとう! – alf

1

あなたは、ファイルへのObjectOutputStreamsを追加することはできません。それらはヘッダーとあなたが書いたオブジェクトを含んでいます。あなたのテクニックを改訂してください。

また、あなたのEOF検出が間違っています。 EOFExceptionを別途キャッチする必要があります。 OptionalDataExceptionは完全に異なるものを意味します。

0

これはあなたが異なったファイルの終わりを処理するためのコードを以下に記載さ従うことができ、私

System.out.println("Nombre del archivo ?"); 
        nArchivo= sc.next(); 
        sc.nextLine(); 
        arreglo=new ArrayList<SuperHeroe>(); 

        try{ 

         FileInputStream fileIn = new FileInputStream(nArchivo); 
         ObjectInputStream in = new ObjectInputStream(fileIn); 

         while(true){ 
          arreglo.add((SuperHeroe) in.readObject()); 

         } 



        } 

         catch(IOException i) 
         { 
         System.out.println("no hay mas elementos\n elementos cargados desde el archivo:"); 

         for(int w=0;w<arreglo.size();w++){ 
          System.out.println(arreglo.get(w).toString()); 
         } 



         }catch(ClassNotFoundException c) 
         { 
         System.out.println("No encontre la clase Estudiante !"); 
         c.printStackTrace(); 

         return; 
         } 
0

のために働く:

public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { 
    // TODO Auto-generated method stub 

    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E://sample.txt")); 
    oos.writeObject(new Integer(5)); 
    oos.writeObject(new Integer(6)); 
    oos.writeObject(new Integer(7)); 
    oos.writeObject(new Integer(8)); 
    oos.flush(); 
    oos.close(); 

    ObjectInputStream ios = new ObjectInputStream(new FileInputStream("E://sample.txt")); 
    Integer temp; 
    try { 
     while ((temp = (Integer) ios.readObject()) != null) { 
      System.out.println(temp); 
     } 
    } catch (EOFException e) { 

    } finally { 
     ios.close(); 
    } 

} 

これは、いずれかをスローせずに、ファイルから複数の整数オブジェクトを読み書きします例外。

関連する問題