cache Object via a File - Android File Input Output

Android examples for File Input Output:Object Serialization

Description

cache Object via a File

Demo Code


//package com.java2s;
import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;

import java.io.ObjectOutputStream;

public class Main {

    public static boolean cacheObject(String filePath, Object cachedObj) {
        boolean _isObjectCached = false;

        if (null != cachedObj) {
            File _cachedFile = new File(filePath);
            if (_cachedFile.exists()) {
                _cachedFile.delete();//from  ww w  .  ja  v  a2  s  .co  m
            }

            ObjectOutputStream _objOutStream = null;
            try {
                _objOutStream = new ObjectOutputStream(
                        new FileOutputStream(_cachedFile));
                _objOutStream.writeObject(cachedObj);

                _isObjectCached = true;
            } catch (Exception e) {
                e.printStackTrace();
                _cachedFile.delete();
            } finally {
                if (null != _objOutStream) {
                    try {
                        _objOutStream.close();
                        _objOutStream = null;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return _isObjectCached;
    }
}

Related Tutorials