2012-08-07 74 views
1

我目前正在嘗試將當前時間粘貼到Android應用程序的文件中。代碼如下所示,但文件未創建。我已經允許我的應用程序通過清單在SD卡上寫入。有任何想法嗎?在Android上寫入文件問題

Time today = new Time(Time.getCurrentTimezone()); 
    today.setToNow(); 
    try { 
     File myFile = new File("/sdcard/mysdfile.txt"); 
     myFile.createNewFile(); 
     FileOutputStream fOut = new FileOutputStream(myFile); 
     OutputStreamWriter myOutWriter = 
           new OutputStreamWriter(fOut); 
     SimpleDateFormat dF = new SimpleDateFormat("HHMMSS"); 
     StringBuilder current = new StringBuilder(dF.format(today)); 
     myOutWriter.append(current); 
     myOutWriter.close(); 
     fOut.close(); 

    } 
+0

嘗試'File myFile = new File(「sdcard/mysdfile.txt」);'一次。 – Lucifer 2012-08-07 02:47:22

+0

沒有工作。感謝您的建議。 – GGe 2012-08-07 02:53:02

回答

3

您應該使用Environment.getExternalStorageDirectory(),而不是硬編碼/sdcard/路徑。

File file = new File(Environment.getExternalStorageDirectory(), "mysdfile.txt");

我試着運行你的代碼,它崩潰由於dF.format(today)

而不必爲此,

Time today = new Time(Time.getCurrentTimezone()); 
today.setToNow(); 

這本

Date today = new Date(); 

此代碼的工作我的設備上工作得很好。

Date today = new Date(); 

try { 
    File myFile = new File(Environment.getExternalStorageDirectory(), "mysdfile.txt");    
    myFile.createNewFile(); 

    FileOutputStream fOut = new FileOutputStream(myFile); 
    OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); 
    SimpleDateFormat dF = new SimpleDateFormat("HHMMSS"); 
    StringBuilder current = new StringBuilder(dF.format(today)); 
    myOutWriter.append(current); 
    myOutWriter.close(); 
    fOut.close(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
+0

不是100%同意你,我也在我的代碼中使用'sdcard/Dir-Name',它工作正常。 – Lucifer 2012-08-07 02:46:48

+1

是的,但並非所有設備都具有相同的路徑名稱。不要硬編碼路徑更安全。因爲它可能會在某些設備上失敗。 – NcJie 2012-08-07 02:48:48

+0

試過了,沒有帶來任何結果。感謝您的努力/建議。 – GGe 2012-08-07 02:49:35

0

嘗試另一種方式如下,

private BufferedWriter buff = null; 
private File logFile = null; 
logFile = new File ("/sdcard/mysdfile.txt"); 
if (!logFile.exists()) 
{ 
    logFile.createNewFile(); 
} 
buff = new BufferedWriter (new FileWriter (logFile,true)); 
buff.append("Write what you want to store"); 
buff.close(); 

你也需要給<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>權限在AndroidManifest.xml中。

+0

沒有工作,感謝您的意見。 – GGe 2012-08-07 03:11:25

+0

你有什麼錯誤?因爲上面的代碼在我的情況下完美工作。請使用您提供的文件許可更新您的問題。 – Lucifer 2012-08-07 03:15:20

+0

這是一個解析日期並將其轉換爲字符串的問題。不過,非常感謝幫助。祝你今天愉快。 – GGe 2012-08-07 03:21:13