Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class MainActivity extends AppCompatActivity {
TextView readText;
EditText writeText;
String name = "Test";
String TAG = "Main";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
readText = findViewById(R.id.textView);
writeText = findViewById(R.id.editText2);
}
public void Read(View view) {
String text = readTextOnInternalStorage(name);
readText.setText(text);
}
public void Write(View view) {
String text = writeText.getText().toString();
writeInternalStorage(name, text);
}
/*
* Function: Write Text to Internal Storage
* Input: file name and data (String type) */
private void writeInternalStorage(String fileName, String data){
try {
FileOutputStream fOut = openFileOutput(fileName, MODE_PRIVATE);
fOut.write(data.getBytes());
fOut.close();
Toast.makeText(getBaseContext(),"file saved",Toast.LENGTH_SHORT).show();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
/* Function: Read Text from Internal Storage
* Input: file name
* @return: text */
private String readTextOnInternalStorage(String fileName){
String data = "";
try {
FileInputStream fin = openFileInput(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(fin, "UTF-8"));
String aDataRow = "";
int n = 0;
while ((aDataRow=reader.readLine()) != null){
n++;
if (n > 1){
//More line
data += "\n" + aDataRow;
}else {
//One line
data = aDataRow;
}
}
Toast.makeText(getBaseContext(),"file read",Toast.LENGTH_SHORT).show();
} catch (java.io.IOException e) {
e.printStackTrace();
}
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment