Code snippet to save/fetch data from file system

To save data from file system you need to add write access storage system permission in application’s manifest.

You can write data in internal as well as on external sd card.

Code to write data on disc


 protected static void saveDataOnDisk(String data) {

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

try {

ObjectOutput objectOutput = new ObjectOutputStream(byteArrayOutputStream);

objectOutput.writeObject(data);

byte[] buffer = byteArrayOutputStream.toByteArray();

File loginDataFile = (new File(filePath)); // file path where you want to write your data

loginDataFile.createNewFile();

FileOutputStream fileOutputStream = new FileOutputStream(loginDataFile);

fileOutputStream.write(buffer);

fileOutputStream.close();

objectOutput.flush();

objectOutput.close();

byteArrayOutputStream.flush();

byteArrayOutputStream.close();

Log.i(“SAVE”, ”———————-DONE SAVING”);

} catch(IOException ioe) {

Log.i(“SAVE”, “———serializeObject|”+ioe);

}

}

Here is code snippet to save bitmap data on file system


File file = new File(filePath); // file path where you want to // save data.

FileOutputStream fileOutputStream = new FileOutputStream(file);

bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream); //bitmap is Bitmap object which you want to save on disc.

fileOutputStream.flush(); fileOutputStream.close();

code to fetch Data From disc

private static Object getDataFromDisk() {

try {

FileInputStream fileInputeStream = new FileInputStream(FilePath);

ObjectInputStream objectInputStream = new ObjectInputStream(fileInputeStream);

Object data = (Object) objectInputStream.readObject();

objectInputStream.close();

fileInputeStream.close();

return dataModel;

} catch (Exception error) {

Log.i(“FETCH”, ”—-getDataFromDisk———ERROR while reading|” + error);

}

return null;

}