[英]file disappearing from SD card
我在SD卡上創建文本文件並附加到要與gmail應用程序一起發送的電子郵件時遇到問題。 在gmail應用中將其附加到電子郵件后,該電子郵件將永遠處於紅色的“正在發送...”狀態。 該文件是使用下面的createCSVfile()創建的。
調試代碼,在不同時間啟動我的應用程序時,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();
}
錯誤是:
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.