2012-08-28 8 views
5

teraz im próbuje użyć tegoJak napisać ArrayList do pliku i pobrać go?

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

w celu zaoszczędzenia „returnlist”, który jest ArrayList do pliku „CalEvents” teraz moje pytanie brzmi, czy to dobry sposób, żeby to zrobić? i jak mogę odzyskać listę?

z góry dzięki

+0

wrócić Używaj ObjectInputStream() readObject (.); i sprawdź instancję ArrayList – Yahor10

Odpowiedz

5

Czy to jest to, co chcesz zrobić?

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: można uprościć:

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(); 
} 

Zakładając, że jesteś w klasie, która rozciąga Context (jak Activity). Jeśli nie, będziesz musiał wywołać metodę openFileInput() na obiekcie, który rozszerza się o Context.

+0

To się udało, dziękuję :))) –

0

Zastosowanie tej metody do pisania ArrayList w pliku

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

Wymieniony link nie działa! Czy mógłbyś zaktualizować swój komentarz? –

+0

zrobione! @robot_alien –

Powiązane problemy