2012-08-28 8 views
5

ora im cercando di utilizzare questoCome scrivere un ArrayList per file e recuperarlo?

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

al fine di risparmiare "returnlist", che è un ArrayList al file "CalEvents" Ora la mia domanda è, è che il modo giusto per farlo? e come posso recuperare la lista?

grazie in anticipo

+0

Per tornare Usa ObjectInputStream() readObject().; e controlla l'istanza di ArrayList – Yahor10

risposta

5

E 'questo quello che vuoi fare?

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: può essere semplificata:

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

Supponendo che ci si trova in una classe che estende Context (come Activity). In caso contrario, sarà necessario chiamare il metodo openFileInput() su un oggetto che si estende Context.

+0

Che l'ha fatto, grazie :))) –

0

Utilizzare questo metodo per scrivere il vostro Arraylist in un file

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

Il link citato non funziona! Potresti aggiornare il tuo commento? –

+0

fatto! @robot_alien –

Problemi correlati