Android: 写入外部存储器的文件未显示

Android: File written in external storage is not showing

我正在尝试编写一个文本文件并将其保存在 android 外部存储器中,但是文件没有显示,而且我没有收到任何错误。

这是我的代码:

String r;
String fname= "readme.txt";
r = Environment.getExternalStorageDirectory().toString();

File myDir = new File(r);    
if (!myDir.exists()) {
    myDir.mkdirs();
}

File file = new File (myDir, fname);
if (file.exists ())
    file.delete (); 

try {
    FileOutputStream out = new FileOutputStream(file);
    Out.write(wfile)
    out.flush();
    out.close();
} catch (Exception e) {
     e.printStackTrace();
}

尝试以下操作。您可以根据需要添加验证以检查文件是否存在。

        File file =  new 
File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "readme.txt");
        FileOutputStream out = new FileOutputStream(file);
        out.write(wfile);
        out.flush();
        out.close();
        MediaScannerConnection.scanFile(mContext, new String[] { file.toString() }, null,new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
                Log.i("ExternalStorage", "Scanned " + path + ":");
                Log.i("ExternalStorage", "-> uri=" + uri);
            }
       });

仅供参考,Environment.DIRECTORY_DOCUMENTS 可能不存在于旧的 android 版本中。然后你可能需要添加一个验证来检查它,如果没有则创建一个目录。