2016-02-18 253 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; 
      } 
     }