2013-03-06 102 views
0

我正在尝试使用时间戳作为名称保存文件。当我自己命名文件时,我可以保存文件没有问题,但是当我尝试使用时间戳时,它不起作用。这是我的代码:使用时间戳保存文件

 Long tsLong = System.currentTimeMillis()/1000; 
     String ts = tsLong.toString(); 

     File newxmlfile = new File(Environment.getExternalStorageDirectory() 
       + ts); 
     try { 
      newxmlfile.createNewFile(); 
     } catch (IOException e) { 
      Log.e("IOException", "exception in createNewFile() method"); 
     } 

     FileOutputStream fileos = null; 
     try { 
      fileos = new FileOutputStream(newxmlfile); 
     } catch (FileNotFoundException e) { 
      Log.e("FileNotFoundException", "can't create FileOutputStream"); 
     } 

有没有人知道如何做到这一点?

编辑(求助):我改变了下面的行,它使用时间戳保存文件作为一个XML文件。

File newxmlfile = new File(Environment.getExternalStorageDirectory() 
       ,ts + ".xml"); 
+0

你得到了哪个错误? – 2013-03-06 14:02:00

+0

-1不定义“不起作用” – njzk2 2013-03-06 14:02:50

回答

5

我想你正在创建一个无效路径的文件。

当你在做字符串concatination:

Environment.getExternalStorageDirectory() + ts 

...您的时间戳123456添加到文件的路径(像)/mnt/sdcard。而你最终像一个无效的路径:

/mnt/sdcard14571747181 

(你没有带已取得了写入该文件,因为它不是外部目录里面。)

要么你添加一个文件你自己或者你创建文件:

File newxmlfile = new File(Environment.getExternalStorageDirectory(), ts); 
                    ^^ 
                   the change