read Object from File - Android File Input Output

Android examples for File Input Output:Object Serialization

Description

read Object from File

Demo Code


//package com.java2s;

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

public class Main {
    public static Object readObj(File dir, String fileName) {

        try {/* ww  w.  j av a2 s  .  co m*/

            File f = new File(dir, fileName);
            if (f.exists())
                return readObj(f);

        } catch (Exception e) {

            e.printStackTrace();
        }

        return null;
    }

    public static Object readObj(File f) {
        Object obj = null;
        ObjectInputStream oic = null;
        try {

            oic = new ObjectInputStream(new FileInputStream(f));
            obj = oic.readObject();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            closeInStream(oic);
        }
        return obj;
    }

    public static void closeInStream(InputStream input) {
        try {
            if (input != null)
                input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials