Java tutorial
//package com.java2s; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import android.text.TextUtils; public class Main { public static final int FILE_ERROR = -1; public static final int FILE_CREATE = 0; public static final int FILE_EXISTS = 1; public static final int FILE_EXISTS_NULL = 2; public static final String FILE_SUFFIX = ".dat"; public static Object readObject(String filePath, String fileName) { String path = checkFilePath(filePath, fileName); if (path != null) { int fileStatus = checkFileStatus(filePath, fileName); return readObject(path, fileStatus); } return null; } public static Object readObject(String path, int fileStatus) { if (!TextUtils.isEmpty(path) && fileStatus == FILE_EXISTS) { try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(path)); Object mObject = in.readObject(); in.close(); return mObject; } catch (Exception e) { } } return null; } public static String checkFilePath(String dirPath, String fileName, String suffix) { if (!TextUtils.isEmpty(dirPath) && !TextUtils.isEmpty(fileName)) { if (suffix != null) { return dirPath + "/" + fileName + suffix; } else { return dirPath + "/" + fileName + FILE_SUFFIX; } } return null; } public static String checkFilePath(String dirPath, String fileName) { return checkFilePath(dirPath, fileName, null); } public static int checkFileStatus(String dirPath, String fileName, String suffix) { int fileStatus; String filePath = checkFilePath(dirPath, fileName, suffix); if (filePath == null) { return fileStatus = FILE_ERROR; } try { File dirFile = new File(dirPath); if (!dirFile.exists()) { dirFile.mkdirs(); } File mFile = new File(filePath); if (!mFile.exists()) { fileStatus = FILE_CREATE; mFile.createNewFile(); } else { long size = mFile.length(); if (size > 0) { fileStatus = FILE_EXISTS; } else { fileStatus = FILE_EXISTS_NULL; } } } catch (IOException e) { e.printStackTrace(); return FILE_ERROR; } return fileStatus; } public static int checkFileStatus(String dirPath, String fileName) { return checkFileStatus(dirPath, fileName, null); } }