Reputation: 634
I want that whatever I written in edit text field in an app to be automatically save in a .txt file. So that I can retrieve this file directly from there and send to any one from a single button. My problem is that how can I save directly in a .txt format.
Upvotes: 2
Views: 7233
Reputation: 628
This code snippet will copy your text into a string when the text is changed, and calls a function to write to the private files directory of your application.
String YourTextString;
YourTextField.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {
YourTextString = YourTextField.getText().toString();
writeToFile(YourTextString);
}
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
});
public void writeToFile(String data) {
try {
OutputStreamWriter MyOutputStreamWriter = new OutputStreamWriter(mContext.openFileOutput("YourFileName.txt", Context.MODE_PRIVATE));
MyOutputStreamWriter.append(data);
MyOutputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
Edit: If you want to read from the file, you can use this function (if the path parameter is empty, the code will read a file from the private files directory, if you give it a path, it will read the file you specified):
public String readFromFile(String path) {
String ret = "";
if(path==""){
try {
InputStream inputStream = mContext.openFileInput(FileName);
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).append("\n");
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
}
else
{
File file = new File(path);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader buf = new BufferedReader(new FileReader(file));
while ( (receiveString = buf.readLine()) != null ) {
stringBuilder.append(receiveString).append("\n");
}
buf.close();
ret = stringBuilder.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
Upvotes: 2
Reputation: 613
Just get the content of your EditText
and save it to a file. Google provides a documentation for this last part.
Upvotes: 0