2016-11-18 108 views
-1

我想開發一個程序,在特定的目錄(.txt文件)中創建一個文件並在其中存儲一些數據(例如字符串)。我也希望文件可以被用戶訪問(如果我去文件資源管理器,我可以查看我創建的文件,也可以用另一個程序或其他東西編輯它)。如何在Android中的特定目錄中創建.txt文件?

我試過很多東西,但是我無法管理這個工作。

這裏是我使用ATM代碼:

public void createFile(View view) throws IOException { 

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd"); 
    Date now = new Date(); 
    String fileName = formatter.format(now) + ".txt"; 
    String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Sonda Drive Test"; 

    File mypath = new File(filepath); 
    if(!mypath.exists()) { 
     mypath.mkdir(); 
    } 
    //now the mkdir returns true isntead of false 


    File myfile = new File(mypath, fileName); 

    try{ 
     if(!myfile.exists()){ 
      txtDebug.setText("Não existe ficheiro!"); 
      myfile.createNewFile(); 
     } 
     else{ 
      txtDebug.setText("Já existe ficheiro!"); 
     } 
    }catch (Exception e){ 
     txtDebug.setText("Erro!"); 
    } 
} 

我還添加權限波紋管:

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

的問題是,當我做

myfile.createNewFile(); 

應用程序停止並關閉..但如果我評論該行,它也不會創建任何文件...

我在做什麼錯?

編輯:我管理使這個工作的API 22.我怎麼能做到API 25?

+1

'程序Crashes'究竟你是什麼意思?你有什麼異常/堆棧跟蹤?請[編輯] int LogCat的詳細日誌輸出。由於缺乏背景而投票結束。 –

+0

'mypath.mkdir();'。檢查返回值,因爲它可能無法創建目錄。如果它返回false,則向用戶顯示敬酒,並返回。 – greenapps

+0

您可能會因爲「myfile」不存在而需要檢查該文件是否存在if(!myfile.exists()) –

回答

0

你把mypath中的路徑,但你定義爲mypath中文件

+0

好吧,那麼我如何將mypath定義爲路徑呢? –

+0

布魯諾不聽布魯諾。 – greenapps

+0

@greenapps哈哈,好的 –

相關問題