我的应用程序应该将文件保存到一个地方,当您将手机/平板电脑连接到计算机时,您可以通过系统文件资源管理器查看它们。
这是我实现文件写入的方式:
protected String mDir = Environment.DIRECTORY_DOCUMENTS;
protected File mPath = Environment.getExternalStoragePublicDirectory(mDir);
protected void writeLogFile(String filename) {
File f = new File(mPath, filename + ".txt");
f.getParentFile().mkdirs();
try (BufferedWriter bw = new BufferedWriter(new FileWriter(f, false))) {
// Details omitted.
} catch (Exception e) {
e.printStackTrace();
return;
}
makeText("Wrote " + f.getAbsolutePath());
}
这是我将 Sony Xperia Z4 平板电脑连接到 Windows 时看到的内容(注意缺少文档文件夹):
这是写入文件的目录(使用上面的实现):
我的实现有什么问题?
最佳答案
What is wrong with my implementation?
MediaStore
尚未发现您新创建的文件。您在 Windows 以及许多设备上的“图库”应用程序中看到的内容是基于 MediaStore
的内容。已编入索引。使用
MediaScannerConnection
及其scanFile()
方法告诉MediaStore
关于您的文件,一旦您将数据写入磁盘:public void scanFile(Context ctxt, File f, String mimeType) {
MediaScannerConnection
.scanFile(ctxt, new String[] {f.getAbsolutePath()},
new String[] {mimeType}, null);
}
或者,在 Kotlin 中:
fun scanFile(ctxt: Context, f: File, mimeType: String) {
MediaScannerConnection.scanFile(ctxt, arrayOf(f.getAbsolutePath()), arrayOf(mimeType), null)
}
关于java - 如何将文件写入 Android 中的外部公共(public)存储,以便它们在 Windows 中可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48013542/