2012-06-10 51 views
2

消失我有創造SD卡上的文本文件中的問題被附加到電子郵件與Gmail應用程序發送。 當Gmail應用附加到電子郵件,在紅色的電子郵件攤位「發送...」狀態,直到永遠。該文件使用下面的createCSVfile()創建。文件從SD卡

調試我的代碼,啓動我的應用程序不同的時間,csv_file.exists()始終返回false,因爲如果文件沒有找到,並且每個應用程序運行時創建。 但是,使用文件管理器,我可以看到文件是存在的之間,並且在運行。

請幫忙嗎? 感謝

File csv_file = null; 
String createCSVfile() { 
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { 
     csv_file = new File(getExternalFilesDir(null) + File.separator + "InOutStats.txt"); 
     if (csv_file != null) { 
      if(csv_file.exists()){ 
       Log.v("CSV_FILE", "Stat file " + csv_file.toString() +" already there!"); 
      }else{ 
       csv_file.getParentFile().mkdirs(); 
       try { 
        boolean bool = csv_file.createNewFile(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
      FileWriter fWriter = null; 
      try { 
       fWriter = new FileWriter(csv_file); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      BufferedWriter writer = new BufferedWriter(fWriter); 
      try { 
       writer.write("Some text here!!! " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())); 
       writer.newLine(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      try { 
       writer.flush(); 
       writer.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    }else{ 
     Log.v("CSV_FILE", "NO SD CARD HERE???"); 
    } 
    return csv_file.toString(); 
} 

回答

0

的錯誤是:

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()) 

這應該是

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) 

我只看到了兩個非常小的 「錯誤」:

[風格問題]

csv_file = new File(getExternalFilesDir(null) + File.separator + "InOutStats.txt"); 

應該

csv_file = new File(getExternalFilesDir(null), "InOutStats.txt"); 

,否則你正在使用File.toString()

[最小碼]

刪除應該是:

csv_file.createNewFile(); 

第二次嘗試

嘗試更換

if (csv_file != null) { 
     if(csv_file.exists()){ 
      Log.v("CSV_FILE", "Stat file " + csv_file.toString() +" already there!"); 
     }else{ 
      csv_file.getParentFile().mkdirs(); 
      try { 
       boolean bool = csv_file.createNewFile(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

 { 

這消除了存在測試,mkdirs和不需要單獨的文件創建。 完成嘗試限制錯誤區域。

而且使用的是文本的默認平臺編碼;你可以把它明確:

new FileWriter(csv_file, "UTF-8") 
+0

嗨。我按照你的建議應用了這兩個改變,但一切都一樣。事實上,當我只將一個靜態字符串打印到文件中並且新的File()可以被賦予整個路徑時,發生了同樣的問題。 – DrWolf

+0

再次嗨。很奇怪。我在其他兩部手機中測試了相同的代碼,並且電子郵件發送正確。不知道發生了什麼事。謝謝 – DrWolf

+0

也許物理文件系統被緩衝,而不是直接寫入磁盤/ SD卡。在其他手機上測試的好主意。 –