read/write an object to file
Asked Answered
B

3

10

here is the code : my mission is to serialize an my object(Person) , save it in a file in android(privately), read the file later,(i will get a byte array), and deserialize the byta array.

       public void setup()
    {

           byte[] data = SerializationUtils.serialize(f);


             WriteByteToFile(data,filename); 



    }
Person p =null ;
    public void draw()
    {
        File te = new File(filename);
         FileInputStream fin = null;


             try {
                fin=new FileInputStream(te);
                byte filecon[]=new byte[(int)te.length()];
                fin.read(filecon);
                String s = new String(filecon);
                System.out.println("File content: " + s);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }






        text(p.a,150,150);

    }

and my function :

public void WriteByteToFile(byte[] mybytes, String filename){

        try {

        FileOutputStream FOS = openFileOutput(filename, MODE_PRIVATE);
        FOS.write(mybytes);
        FOS.close();


        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("done");









    }

it is returning a filenotfoundexception .

(i am new at this, so please be patient and understanding)

EDIT ::this is how i am (trying to ) read, (for cerntainly)

ObjectInputStream input = null;
    String filename = "testFilemost.srl";
    try {
        input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
    } catch (StreamCorruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        Person myPersonObject = (Person) input.readObject();
        text(myPersonObject.a,150,150);
    } catch (OptionalDataException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        input.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

and for reading :::

if(mousePressed)

{
    Person myPersonObject = new Person();
    myPersonObject.a=432;
    String filename = "testFilemost.srl";
    ObjectOutput out = null;

    try {
        out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        out.writeObject(myPersonObject);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Bargainbasement answered 11/8, 2013 at 7:41 Comment(1)
you don't have file in filesystem. First create a file then open it.Basil
B
19

You don't need to use the 'byte array' approach. There is an easy way to (de)serialize objects.

EDIT: here's the long version of code

Read:

public void read(){
    ObjectInputStream input;
    String filename = "testFilemost.srl";

    try {
        input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
        Person myPersonObject = (Person) input.readObject();
        Log.v("serialization","Person a="+myPersonObject.getA());
        input.close();
    } catch (StreamCorruptedException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

}

Write:

public void write(){
    Person myPersonObject = new Person();
    myPersonObject.setA(432);
    String filename = "testFilemost.srl";
    ObjectOutput out = null;

    try {
        out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
        out.writeObject(myPersonObject);
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Person class:

public class Person implements Serializable {
    private static final long serialVersionUID = -29238982928391L;
    int a;

    public int getA(){
        return a;
    }

    public void setA(int newA){
        a = newA;
    }
}
Backboard answered 11/8, 2013 at 8:7 Comment(11)
i just need to store it in internal directory.Bargainbasement
You just have to use getFilesDir() instead of Environment.getExternalStorageDirectory()Backboard
i cant seem to get it to work. in my void setup, i am reading it. (void setup runs only once). and in my void draw, i am checking for a touch,if true, it writes an object to the file. the next time i run the app, the value read in void setup is still 0. i dont know what is wrong.Bargainbasement
also, what is the location of this file that (has not yet)is being saved?Bargainbasement
It's in Data > Data > app.package.name > filesBackboard
^i can see the file getting created,but in reading, it is not printing the assigned value.Bargainbasement
can you show me your code (the part you write and read including the line where you created your object)?Backboard
see my edit. I've tested my code. It would work for you, too.Backboard
YES! thats what i was talking about. thank you brother! (btw, was the way i was acessing the object the problem?)Bargainbasement
I'm not sure why you got a '0' value. You'd have to dig through your stack trace. PS. Please keep in mind that you cannot serialize a nested class (a class within a class). Cheers.Backboard
okay, will surely keep that in mind could you give me your email id, where i could contact you ?Bargainbasement
S
1

FileNotFoundException when creating a new FileOutputStream means that one of the intermediate directories didn't exist. Try

file.getParentFile().mkdirs();

before creating the FileOutputStream.

Swound answered 14/8, 2013 at 8:39 Comment(0)
Y
0

Add this code to manifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>

Go to phone setting/applications/your_app/permissions/ allow files and media permission. You can ask permission via by code and when user enter app program will ask permission. If you want I can give you code.

All writen and readen objects must be serializable.(Must implements Serializable interface) If A class extends B class, to set B class serializable is enough. And add this code to writen and readen class:

    private static final long serialVersionUID = 1L;

Write to external memory:

public static void writeToExternal(Serializable object, String filename) {
    try {
        //File root = new File(Environment.getExternalStorageDirectory(), "MyApp");
        //or
        File root = new File("/storage/emulated/0/MyApp/");
        if (!root.exists()) {
            root.mkdirs();
        }
        File file = new File(root, filename);
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutput out = new ObjectOutputStream(fos);
        out.writeObject(object);
        out.flush();
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

If you want to write to internal memory(This memory is not visible and doesn't need permission. This is your app stored in. For this, you can use getFilesDir() instead of getExternalStorageDirectory(). More about https://developer.android.com/reference/android/content/ContextWrapper#getFilesDir%28%29 https://developer.android.com/reference/android/os/Environment.html#getDataDirectory%28%29 https://gist.github.com/granoeste/5574148 https://source.android.com/docs/core/storage

public static void writeToInternal(Context context, Serializable object, String filename){
    try {
        //File root1 = new File(context.getFilesDir(), "MyApp");
        //or
        File root = new File("/data/user/0/com.example.myapplication/files/MyApp/");
        if (!root.exists()) {
            root.mkdirs();
        }
        File file = new File(root, filename);
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutput out = new ObjectOutputStream(fos);
        out.writeObject(object);
        out.flush();
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Read an object:

public static Object read(String filename) {
    try {
        File file = new File("/storage/emulated/0/MyApp/" + filename);
        FileInputStream fis = new FileInputStream(file);
        ObjectInputStream input = new ObjectInputStream(fis);
        Object data = (Object) input.readObject();
        input.close();
        return data;
    } catch (StreamCorruptedException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

When you call read method you must cast to your readen and writen class.(For example Person p = (Person)read("file.txt"); Import all classes and run.

Yonatan answered 27/8, 2022 at 8:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.