harveyslash
harveyslash

Reputation: 6014

read/write an object to file

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

Upvotes: 10

Views: 15409

Answers (3)

Kanan
Kanan

Reputation: 242

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.

Upvotes: 0

user207421
user207421

Reputation: 310869

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

file.getParentFile().mkdirs();

before creating the FileOutputStream.

Upvotes: 1

growic
growic

Reputation: 330

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

Upvotes: 19

Related Questions