2013-03-06 105 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