Skip to content

Instantly share code, notes, and snippets.

@whitfin
Created January 28, 2014 21:07
Show Gist options
  • Save whitfin/8676531 to your computer and use it in GitHub Desktop.
Save whitfin/8676531 to your computer and use it in GitHub Desktop.
Simple class to write a JSON object to a file, and read it back into JSON. Useful for data storing on Android.
package com.zackehh.example;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import android.content.Context;
/**
* Allows the reading/writing of an object from/to a file
* inside the application's /data directory. Allows for
* more efficient storing of objects such as arrays instead
* of within SharedPreferences
*
* @author Isaac Whitfield
* @version 31/07/2013
*/
public class WriteObjectFile {
private Context parent;
private FileInputStream fileIn;
private FileOutputStream fileOut;
private ObjectInputStream objectIn;
private ObjectOutputStream objectOut;
private Object outputObject;
private String filePath;
public WriteObjectFile(Context c){
parent = c;
}
public Object readObject(String fileName){
try {
filePath = parent.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + fileName;
fileIn = new FileInputStream(filePath);
objectIn = new ObjectInputStream(fileIn);
outputObject = objectIn.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (objectIn != null) {
try {
objectIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return outputObject;
}
public void writeObject(Object inputObject, String fileName){
try {
filePath = parent.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + fileName;
fileOut = new FileOutputStream(filePath);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(inputObject);
fileOut.getFD().sync();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (objectOut != null) {
try {
objectOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
@M-Khay
Copy link

M-Khay commented Apr 16, 2015

This is giving me Error everytime i'm tyring to save my JSON object passed to writeObject() function . The exact error is :
java.io.WriteAbortedException: Read an exception; java.io.NotSerializableException: org.json.JSONObject

@EminaCirkic
Copy link

You need to add implements Serializable to you Object class.

@FuriosoJack
Copy link

Esta érfecto para usarla con Gson

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment