2016-02-18 266 views
18

我想写的东西到一个文件中。我发现这个代码:将一个字符串写入文件

private void writeToFile(String data) { 
    try { 
     OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE)); 
     outputStreamWriter.write(data); 
     outputStreamWriter.close(); 
    } 
    catch (IOException e) { 
     Log.e("Exception", "File write failed: " + e.toString()); 
    } 
} 

代码似乎很符合逻辑,但我无法找到我的电话的config.txt文件。
我怎样才能检索到该文件,其中包含字符串?

+0

您是否确实需要将某些东西写入txt文件?如果不考虑使用SharedPreferences。 http://developer.android.com/guide/topics/data/data-storage.html#pref – Sebastian

回答

31

未指定路径,您的文件将被保存在您的应用空间(/data/data/your.app.name/)。

因此,你最好将文件保存到外部存储(这不一定是SD卡,它可以是默认存储)。

你可能想挖入主题,通过读取official docs

在合成:

添加此权限将您的清单:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

它包括读取权限,所以没有需要指定它。

保存在指定的位置文件(这是从我的生活鳕拍摄,所以我敢肯定它的工作原理):

public void writeToFile(String data) 
{ 
    // Get the directory for the user's public pictures directory. 
    final File path = 
     Environment.getExternalStoragePublicDirectory 
     (
      //Environment.DIRECTORY_PICTURES 
      Environment.DIRECTORY_DCIM + "/YourFolder/" 
     ); 

    // Make sure the path directory exists. 
    if(!path.exists()) 
    { 
     // Make it, if it doesn't exit 
     path.mkdirs(); 
    } 

    final File file = new File(path, "config.txt"); 

    // Save your stream, don't forget to flush() it before closing it. 

    try 
    { 
     file.createNewFile(); 
     FileOutputStream fOut = new FileOutputStream(file); 
     OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); 
     myOutWriter.append(data); 

     myOutWriter.close(); 

     fOut.flush(); 
     fOut.close(); 
    } 
    catch (IOException e) 
    { 
     Log.e("Exception", "File write failed: " + e.toString()); 
    } 
} 

[编辑] OK尝试这样的(不同的道路 - 在外部存储的文件夹):

String path = 
     Environment.getExternalStorageDirectory() + File.separator + "yourFolder"; 
    // Create the folder. 
    File folder = new File(path); 
    folder.mkdirs(); 

    // Create the file. 
    File file = new File(folder, "config.txt"); 
+0

我找不到我的下数据的应用程序/数据 – jason

+0

这是'/数据/数据/ ...''没有数据/ data/...',如果您没有root访问权限,则无法使用文件资源管理器查看。 –

+0

我正在搜索整个手机的config.txt,它找不到任何东西。 – jason

0

这种方法需要文件名&数据字符串作为输入和转储他们SD卡上的文件夹中。 如果需要,您可以更改文件夹的名称。

返回类型为布尔值取决于FileOperation的成功或失败。

重要提示:尽量做到在异步任务,文件IO使事业ANR的主线程。

public boolean writeToFile(String dataToWrite, String fileName) { 

      String directoryPath = 
        Environment.getExternalStorageDirectory() 
          + File.separator 
          + "LOGS" 
          + File.separator; 

      Log.d(TAG, "Dumping " + fileName +" At : "+directoryPath); 

      // Create the fileDirectory. 
      File fileDirectory = new File(directoryPath); 

      // Make sure the directoryPath directory exists. 
      if (!fileDirectory.exists()) { 

       // Make it, if it doesn't exist 
       if (fileDirectory.mkdirs()) { 
        // Created DIR 
        Log.i(TAG, "Log Directory Created Trying to Dump Logs"); 
       } else { 
        // FAILED 
        Log.e(TAG, "Error: Failed to Create Log Directory"); 
        return false; 
       } 
      } else { 
       Log.i(TAG, "Log Directory Exist Trying to Dump Logs"); 
      } 

      try { 
       // Create FIle Objec which I need to write 
       File fileToWrite = new File(directoryPath, fileName + ".txt"); 

       // ry to create FIle on card 
       if (fileToWrite.createNewFile()) { 
        //Create a stream to file path 
        FileOutputStream outPutStream = new FileOutputStream(fileToWrite); 
        //Create Writer to write STream to file Path 
        OutputStreamWriter outPutStreamWriter = new OutputStreamWriter(outPutStream); 
        // Stream Byte Data to the file 
        outPutStreamWriter.append(dataToWrite); 
        //Close Writer 
        outPutStreamWriter.close(); 
        //Clear Stream 
        outPutStream.flush(); 
        //Terminate STream 
        outPutStream.close(); 
        return true; 
       } else { 
        Log.e(TAG, "Error: Failed to Create Log File"); 
        return false; 
       } 

      } catch (IOException e) { 
       Log.e("Exception", "Error: File write failed: " + e.toString()); 
       e.fillInStackTrace(); 
       return false; 
      } 
     }