2012-08-07 71 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