问题描述
我有一个应用程序,它将用户输入的数据保存到文件(内部存储)中,并在启动时加载该文件并显示内容.我想知道:在哪里可以找到我的文件(data.txt
)?另外,如果在加载文件时输入"Hello"然后输入"World",则在同一行中会看到"HelloWorld",但我希望在两行中分别打印"Hello"和"World".
I have an app that saves into a file (internal storage) data input by the user and at startup it loads this file and shows the contents. I would like to know: where can I find my file (data.txt
)?In addition, if I input "Hello" and then "World" when I load the file, I see "HelloWorld" in the same line but I want "Hello" and "World" printed on two different lines.
用于保存文件:
public void writeToFile(String data) {
try {
FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
用于加载文件:
public String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("data.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();
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());
}
return ret;
}
谢谢.
[UPDATE]
我在每次输入后都插入了"\ n":
I've inserted "\n" after every input:
user = (EditText) v.findViewById(R.id.username);
writeToFile(user.getText().toString() + "\n");
但是当我打印文件时,它们总是在同一行上.
But when I print my file, they are always on the same line.
推荐答案
您可以使用YourActivity.this.getFilesDir().getAbsolutePath()
查找由openFileOutput
创建的目录路径.
You can find the path of the directory, which is created by openFileOutput
, by using YourActivity.this.getFilesDir().getAbsolutePath()
.
在文件中写入单词后使用line.separator
,例如:
Use line.separator
after writing a word in a file, for example:
String separator = System.getProperty("line.separator");
outputStreamWriter.write(data);
outputStreamWriter.append(separator);
...
或者您也可以使用replaceAll
将String分成多行:
Or you can also use replaceAll
to break String into multiple lines:
String separator = System.getProperty("line.separator");
data=data.replaceAll(" ",separator);
这篇关于Android FileOutputStream位置保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!