如何将文件写入 Android 中的外部公共存储,以便它们在 Windows 中可见? [英] How to write files to external public storage in Android so that they are visible from Windows?

查看:29
本文介绍了如何将文件写入 Android 中的外部公共存储,以便它们在 Windows 中可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My app should save files to a place where, when you connect your phone/tablet to a computer, you can see them through the system file explorer.

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

This is the way I implemented file writing:

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

This is what I see when I connect my Sony Xperia Z4 tablet to Windows (notice missing documents folder):

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

This is the directory to which the file is written (using above implementation):

我的实现有什么问题?

推荐答案

我的实现有什么问题?

What is wrong with my implementation?

MediaStore 尚未发现您新创建的文件.您在 Windows 中看到的内容 —并在许多设备上的图库"应用程序中—基于 MediaStore 已编入索引的内容.

MediaStore has not discovered your newly-created files yet. What you see in Windows — and in many on-device "gallery" apps — is based on what MediaStore has indexed.

使用 MediaScannerConnection 及其 scanFile() 方法告诉 MediaStore 关于您的文件,一旦您将数据写入磁盘:

Use MediaScannerConnection and its scanFile() method to tell MediaStore about your file, once you have written out your data to disk:

public void scanFile(Context ctxt, File f, String mimeType) {
    MediaScannerConnection
        .scanFile(ctxt, new String[] {f.getAbsolutePath()},
                  new String[] {mimeType}, null);
}

或者,在 Kotlin 中:

or, in Kotlin:

fun scanFile(ctxt: Context, f: File, mimeType: String) {
  MediaScannerConnection.scanFile(ctxt, arrayOf(f.getAbsolutePath()), arrayOf(mimeType), null)
}

这篇关于如何将文件写入 Android 中的外部公共存储,以便它们在 Windows 中可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆