创建一个 txt 文件并在文件管理器中查看它

Creating a txt file and viewing it in the File manger

我创建了一个 android 应用程序,它通过 EditText 从用户那里获取输入并将它们写入 phone 内部存储中的 name.txt 文件。是否可以在 phone 的文件管理器中打开文本文件?我尝试使用 getFilesDir().getAbsolutePath()+"/"+FILE_NAME 获取文件路径。但是无法在文件管理器中找到该文件。

每个应用程序都有私人存储空间,可以从应用程序本身访问,然后 public 其他应用程序也可以访问的存储空间/sdcard/...(它需要从系统获得存储权限) 此方法将内容保存在应用程序私有存储中的文件中

public void saveFile(String fileName, String content) {
        try {
            FileOutputStream fOut = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            fOut.write((content).getBytes());

            fOut.flush();
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

如果您希望文件管理器等其他应用程序访问该文件,则需要使用外部存储。内部存储只能由您的应用读取。

在评论中你提出了一个有效的问题 - "What if the phone doesnt have external storage...?"。这在今天并不是真正的问题。参见 https://developer.android.com/training/data-storage/files

Many devices now divide the permanent storage space into separate "internal" and "external" partitions. So even without a removable storage medium, these two storage spaces always exist...

==========

所以将上面的代码更改为:

getExternalFilesDir().getAbsolutePath()+"/"+FILE_NAME

getExternalFilesDirandroid.content.Context class 中的一个方法。所以这个电话将在你的 activity class 中工作,这是一个 Context.

=============

进一步支持外部存储的选择如下,同样来自https://developer.android.com/training/data-storage/files

Internal storage is best when you want to be sure that neither the user nor other apps can access your files.

External storage is the best place for files that don't require access restrictions and for files that you want to share with other apps or allow the user to access with a computer.