在将Android设备连接到计算机后,我无法找到我在文件资源管理器中创建和写入的.csv文件。
我的清单中有WRITE_EXTERNAL_STORAGE
,如此:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
我在主要活动中使用此功能写入文件:
public void exportDatabase() {
File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
+ "/Folder");
boolean var = false;
if (!folder.exists()) {
Log.d(EXPORT_DATA_TAG, "Folder does not exist");
var = folder.mkdir();
Log.d(EXPORT_DATA_TAG, "mkdir() success? " + var);
}
CharSequence contentTitle = getString(R.string.app_name);
final ProgressDialog progDailog = ProgressDialog.show(
this, contentTitle, "Exporting data...",
true);
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
}
};
final String filename = folder.toString() + "/" + "LeadCapture.csv";
Log.d(EXPORT_DATA_TAG,"Writing data to file: " + filename);
new Thread() {
public void run() {
boolean success = writeData(filename);
if (success) {
handler.sendEmptyMessage(0);
Log.d(EXPORT_DATA_TAG,"Write successful to .csv");
} else {
Log.d(EXPORT_DATA_TAG,"Failed to write to .csv");
}
progDailog.dismiss();
}
}.start();
}
这会在我的数据库帮助程序类中调用write函数:
public boolean writeData(String filename){
leadDatabase = openOrCreateDatabase(database_name, MODE_PRIVATE, null);
try {
FileWriter fw = new FileWriter(filename);
Cursor cursor = leadDatabase.rawQuery("select * from " + database_name, null);
fw.append("Index");
fw.append(',');
fw.append("BarcodeData");
fw.append(',');
fw.append("Notes");
fw.append(',');
fw.append('\n');
if (cursor.moveToFirst()) {
do {
fw.append(cursor.getString(0));
fw.append(',');
fw.append(cursor.getString(1));
fw.append(',');
fw.append(cursor.getString(2));
fw.append(',');
fw.append('\n');
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
fw.close();
leadDatabase.close();
return true;
} catch (Exception e) {
Log.d(DATABASE_TAG,"Error: ",e);
leadDatabase.close();
return false;
}
}
Logcat表示该文件已成功写入/storage/sdcard1/Download/Folder/LeadCapture.csv
,但我无法在“下载”文件夹或任何位置找到该文件夹或文件。
我尝试过更改
File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
到
File folder = new File(Environment.getExternalStorageDirectory())
这导致此路径/storage/sdcard1/Folder/LeadCapture.csv
,但我仍然无法在那里找到该文件。我很困惑,因为在关于这个问题的大多数其他问题中,它一直是一个问题,没有WRITE_EXTERNAL_STORAGE
权限,他们不知道文件路径,或者他们写入内部存储器,其中没有一个是这里的情况。理论上,即使我的writeFunction()不正确,它至少应该创建一个我可以看到的空目录。有什么想法吗?
答案 0 :(得分:0)
如果其他人偶然发现:在设备上创建文件和显示文件之间会有延迟。 MediaScanner必须扫描新文件才能显示它们,并且它只会经常运行,或者在设备重置时运行。我在应用程序中添加了以下内容,以便在编写完文件后立即触发媒体扫描:
String[] files = { filename };
MediaScannerConnection.scanFile(getApplicationContext(), files, null, null);