我希望我在应用程序的编辑文本字段中编写的内容能够自动保存在.txt文件中。这样我就可以直接从那里检索这个文件并从一个按钮发送到任何一个文件。 我的问题是如何直接以.txt格式保存。
答案 0 :(得分:2)
此代码段会在文本更改时将文本复制到字符串中,并调用函数写入应用程序的私有文件目录。
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());
}
}
修改强> 如果要从文件中读取,可以使用此函数(如果path参数为空,代码将从私有文件目录中读取文件,如果给它一个路径,它将读取您指定的文件):
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;
}
答案 1 :(得分:0)
只需获取EditText
的内容并将其保存到文件中即可。 Google提供了documentation for this last part。