2012-09-19 111 views
1

这是一个漫长而烦人的一天,我有代码工作,它会创建并写入文件,并在其末尾添加日期和时间。但我必须改变一些事情,并为了我的生活,我看不到我做错了什么。Android将时间戳添加到文件

如果有人能指出我犯的这个简单的错误,那会很好。

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy/hh-mm-ss"); 
Date curDate = new Date(); 
String stringDate = sdf.format(curDate); 
String resultLogFile = "resultsFile " + stringDate; 
File resultsFile = new File(Environment.getExternalStorageDirectory() + resultLogFile); 
if (!resultsFile.exists()) 
{ 
    try 
    { 
     resultsFile.createNewFile(); 
    } 
    catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 
} 
try 
{ 
    BufferedWriter buf = new BufferedWriter(new FileWriter(resultsFile, true)); 
    buf.append(writeToFileString); 
    buf.newLine(); 
    buf.close(); 
} 
catch (IOException e) 
{ 
    e.printStackTrace(); 
} 
+0

在我看来,你正在尝试创建一个类似**“/ mnt/sdcard/resultsFile 22-09-2012/11-22-33”**的文件。这很可能是一个无效的文件名。 'createNewFile()'调用是否成功?此外,您正在将'writeToFileString'追加到文件中,但该变量没有在您发布的代码中声明或设置,所以我不知道这是什么。 –

回答

1

问题是在你的日期格式字符串中的斜线或你试图创建当天和HH-MM-SS文件的文件夹?在这种情况下,您应该删除斜杠周围的空格,并在resultsFile.createNewFile()之前调用resultsFile.mkdirs()以确保目录resultsFile dd-MM-yyyy存在。但是我非常肯定你不需要目录,所以只需要用其他的替换DateFormat中的斜线即可。