Android FileOutputStream 保存文件的位置

16

我有一个应用程序,它将用户输入的数据保存到一个文件(内部存储器)中,启动时加载该文件并显示其内容。我想知道:在哪里可以找到我的文件(data.txt)?

另外,如果我输入“Hello”然后输入“World”,当我加载文件时,我会看到“HelloWorld”在同一行上,但我想要“Hello”和“World”分别打印在两行上。

保存文件的代码:

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;
}

谢谢。

[更新]

我在每个输入之后插入了"\n":

user = (EditText) v.findViewById(R.id.username);
writeToFile(user.getText().toString() + "\n");

但是当我打印文件时,它们总是在同一行。


我该如何设置保存文件的新路径? - xXJohnRamboXx
2个回答

14

我应该在哪里找到我的文件(data.txt)?

您可以通过使用 YourActivity.this.getFilesDir().getAbsolutePath() 来查找由 openFileOutput 创建的目录的路径。

但我想让“Hello”和“World”分别打印在两行上。

在文件中写入一个单词后,请使用 line.separator,例如:

String separator = System.getProperty("line.separator");
outputStreamWriter.write(data);
outputStreamWriter.append(separator);
...

或者您也可以使用replaceAll将字符串拆分为多行:

String separator = System.getProperty("line.separator");
data=data.replaceAll(" ",separator);

您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - xXJohnRamboXx
@xXJohnRamboXx: 你确定在从文件中读取数据然后添加新行吗? - ρяσѕρєя K
1
@xXJohnRamboXx:尝试这样写 :: stringBuilder.append(receiveString); stringBuilder.append("\n"); - ρяσѕρєя K
我将我的内容文件打印到文本视图组件中,但是单词没有分开成行。 - xXJohnRamboXx
@xXJohnRamboXx:要查看文件,请尝试使用DDMS。 - ρяσѕρєя K
显示剩余2条评论

4
我猜你可以在这里找到它:data/data/[你的包名]/... 关于在两行中编写,只需在需要换行时添加“\n”。

我的数据/资料是空的。我刚刚在每个单词后面添加了“\n”,但仍然没有任何输出 :/ - xXJohnRamboXx
如果您想在SD卡中写入数据,请仔细阅读此教程:http://chrisrisner.com/31-Days-of-Android--Day-23%E2%80%93Writing-and-Reading-Files - M. Erfan Mowlaei

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接