2012-08-28 9 views
5

は今、今、私の質問は 「CalEvents」ファイルにArrayListにある「returnlist」を節約するために、このArrayListをファイルに書き込んでそれを取得する方法は?

FileOutputStream fos = getContext().openFileOutput("CalEvents", Context.MODE_PRIVATE); 
    ObjectOutputStream oos = new ObjectOutputStream(fos); 
    oos.writeObject(returnlist); 
    oos.close(); 

を使用しようとイム、それを行うための正しい方法ということでしょうか? リストを取得するにはどうすればよいですか?

ありがとうございました

+0

ファイルであなたのArrayListを書き込むのreadObject(); ArrayListのインスタンスを確認してください – Yahor10

答えて

5

これはあなたのやりたいことですか?

FileInputStream fis; 
try { 
    fis = openFileInput("CalEvents"); 
    ObjectInputStream ois = new ObjectInputStream(fis); 
    ArrayList<Object> returnlist = (ArrayList<Object>) ois.readObject(); 
    ois.close(); 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} catch (ClassNotFoundException e) { 
    e.printStackTrace(); 
} 

EDIT:を簡略化することができる:

FileInputStream fis; 
try { 
    fis = openFileInput("CalEvents"); 
    ObjectInputStream ois = new ObjectInputStream(fis); 
    ArrayList<Object> returnlist = (ArrayList<Object>) ois.readObject(); 
    ois.close(); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

は、あなたが(Activityのような)Contextを拡張するクラスであると仮定すると。そうでなければ、Contextを拡張するオブジェクトに対してopenFileInput()メソッドを呼び出す必要があります。

+0

それ、ありがとう:))) –

0

このメソッドを使用し使用するObjectInputStream()を取り戻すため

public static void write(Context context, Object nameOfClass) { 
    File directory = new File(context.getFilesDir().getAbsolutePath() 
      + File.separator + "serlization"); 
    if (!directory.exists()) { 
     directory.mkdirs(); 
    } 

    String filename = "MessgeScreenList.srl"; 
    ObjectOutput out = null; 

    try { 
     out = new ObjectOutputStream(new FileOutputStream(directory 
       + File.separator + filename)); 
     out.writeObject(nameOfClass); 
     out.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

Complete example here, with Read method

+0

上記のリンクが機能しません!コメントを更新してください。 –

+0

完了! @robot_alien –

関連する問題