Skip to content

Instantly share code, notes, and snippets.

@jackhumbert
Last active January 3, 2016 04:08
Show Gist options
  • Save jackhumbert/8406427 to your computer and use it in GitHub Desktop.
Save jackhumbert/8406427 to your computer and use it in GitHub Desktop.
package com.test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getName();
private static final String FILENAME = "myFile.txt";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // you may need to change this to R.layout.activity_main, or whatever your layout is called
String textToSaveString = "Hello Android";
writeToFile(FILENAME, textToSaveString); // this writes the string to the file (jumps below)
String textFromFileString = readFromFile(FILENAME); // this reads what you just wrote (jumps below)
if ( textToSaveString.equals(textFromFileString) ) // this tests to see if the before and after are the same (they should be)
Toast.makeText(getApplicationContext(), "both string are equal", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "there is a problem", Toast.LENGTH_SHORT).show();
}
private void writeToFile(String filename, String data) {
// this block is similar to what you had before
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(filename, Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e(TAG, "File write failed: " + e.toString());
}
}
private String readFromFile(String filename) {
String ret = "";
try {
// this is reading the same filename that you saved to
InputStream inputStream = openFileInput(filename);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = ""; // string where text will be stored
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString); // store each line (should only be one)
}
inputStream.close();
ret = stringBuilder.toString(); // actually store the string
}
}
catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "Can not read file: " + e.toString());
}
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment