java - 如何将文件写入 Android 中的外部公共(public)存储,以便它们在 Windows 中可见?

标签 java android

我的应用程序应该将文件保存到一个地方,当您将手机/平板电脑连接到计算机时,您可以通过系统文件资源管理器查看它们。

这是我实现文件写入的方式:

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 时看到的内容(注意缺少文档文件夹):

windows file explorer showing tablet contents

这是写入文件的目录(使用上面的实现):

android device monitor showing file system

我的实现有什么问题?

最佳答案

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/

相关文章:

android - 无法在 kotlin android 中以编程方式禁用 EditText

java - 是否长期保留前导零 SQLITE 插入

java - java字节码astore_1和astore_2有什么区别

java - 获取String值的ArrayList的值

java - 运行 Activity 两次(而不是一次)以从 getter 获取值

android - 文件名中有空格的可绘制对象?

android - 当我尝试从 Intent 获取额外对象时出现 RuntimeException

java - Google App Engine Cloud Endpoints userId 为空

java - 缓存 JSON 字符串与 Java 对象

android - 渲染和截图网页