Reading and writing files from/to private storage

Reading and writing files from/to private storage. Using a Context you can access the methods

  • context.openFileInput(filename) for getting an InputStream
  • and context.openFileOutput(filename, Context.MODE_PRIVATE) for an OutputStream,

the rest is standard Java.

Reading a file into a String

String result = null;

try {
    InputStream inputStream = openFileInput("file.txt");

    if (inputStream != null ) {
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String receiveString = "";
        StringBuilder stringBuilder = new StringBuilder();

        while ( (receiveString = bufferedReader.readLine()) != null ) {
            stringBuilder.append(receiveString);
        }

        inputStream.close();
        result = stringBuilder.toString();
    }
} catch (FileNotFoundException e) {
    Log.e(TAG, "File not found: " + e.toString());
} catch (IOException e) {
    Log.e(TAg, "Can not read file: " + e.toString());
}

Write to a file

try {
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(mContext.openFileOutput("file.txt", Context.MODE_PRIVATE));
    outputStreamWriter.write(data);
    outputStreamWriter.close();
} catch (IOException e) {
    Log.e("Exception", "File write failed: " + e.toString());
}