2012-06-10 171 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卡。在其他手机上测试的好主意。 –