2015-01-07 41 views
8

我有一个应用程序保存到用户输入的文件(内部存储)数据,并在启动时加载此文件并显示内容。我会知道:我在哪里可以找到我的文件(data.txt)? 除了,如果我输入“你好”,然后“世界”当我加载文件我看到“HelloWorld”在同一行,但我希望“你好”和“世界”打印在2不同的行。Android FileOutputStream位置保存文件

为了节省文件:

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"); 

但是,当我打印我的文件,他们总是在同一行

+0

如何设置新的路径保存文件? – xXJohnRamboXx

回答

11

我在哪里可以找到我的文件(data.txt)?

可以使用YourActivity.this.getFilesDir().getAbsolutePath()

发现这是由openFileOutput创建的目录路径,但我想“你好”和“世界”印在2条不同的线路。

使用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); 
+0

我的路径是/ data/data/mypackage,但如果我去那里empty..maybe它是必要的我的设备是根植的看到它.. String separator = System.getProperty(“line.separator”); 不工作..字仍然在同一行 – xXJohnRamboXx

+0

@xXJohnRamboXx:你确定当你从文件读取数据然后添加新行? –

+1

@xXJohnRamboXx:尝试它为::'stringBuilder.append(receiveString); stringBuilder.append(“\ n”);' –

3

我想你可以在这里找到:数据/数据/ [你的包名称]/...,只是关于两个单独的行写每当需要转到另一行时添加“\ n”。

+0

我的数据/数据是空的..我刚刚在每个单词后面添加了“\ n”,但没有任何内容:/ – xXJohnRamboXx

+0

更新您的新代码以解决newLine问题 –

+0

如果要在SD卡中写入数据,教程:http://chrisrisner.com/31-Days-of-Android--Day-23%E2%80%93Writing-and-Reading-Files –