【问题标题】:How to write files to external public storage in Android so that they are visible from Windows?如何将文件写入 Android 中的外部公共存储,以便它们在 Windows 中可见?
【发布时间】:2015-12-23 16:45:09
【问题描述】:

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

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

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

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

我的实现有什么问题?

【问题讨论】:

    标签: java android


    【解决方案1】:

    我的实现有什么问题?

    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)
    }
    

    【讨论】:

    • 谢谢,这行得通。我真的认为他们应该在official documentation 中包含这些信息。我认为 MediaStore 最终会自行找到这些文件?
    • @transporter_room_3:是的。有一个小型版的 Googlebot 会定期扫描外部存储,并在重新启动时更新 MediaStore 文件名册。该文件最终会显示出来。
    猜你喜欢
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    相关资源
    最近更新 更多