Search code examples
javaandroidarraysstorageinternal

Read string array from internal storage


I have been searched on the forum for a while now, but can't find my question. I see a lot of examples of how to write a String Array to internal storage, but not how to read them again.

I have a String Array which is saved by:

String FILENAME = "data1";
fos = openFileOutput(FILENAME, Context.MODE_APPEND);
for(int j=1;j<=PupilAmount;j++) {  
    fos.write(pup[j].getBytes());  
} 
fos.close();

But how do I read the variables again, and save it in a new variable on my new Activity?


Solution

  • A string array is serializable. So you can serialize it on a file

    FileOutputStream fout = openFileOutput(FILENAME, Context.MODE_APPEND);
    ObjectOutputStream oos = new ObjectOutputStream(fout);
    oos.writeObject(pup);
    oos.close();
    

    and read back this way:

    FileInputStream fin = openFileInput(FILENAME, Context.MODE_APPEND);
    ObjectInputStream ois = new ObjectInputStream(fin);
    String[] pup = (String[]) ois.readObject();
    ois.close()