1

我目前正在尝试将当前时间粘贴到 Android 应用程序的文件中。代码如下所示,但未创建文件。我已启用我的应用程序通过清单在 SD 卡上写入的权限。有任何想法吗?

    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();

    }
4

2 回答 2

2

您应该使用 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();
}
于 2012-08-07T02:45:20.197 回答
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 中授予权限。

于 2012-08-07T02:58:48.893 回答