Android:如何在本地编写文件并将其保存到下载

时间:2017-01-25 15:19:30

标签: java android

如何在本地编写文件并将其保存到Android中的Downloads应用程序?

Android版:Nougut

该文件未在Downloads中显示。这是我的代码:

File file = new File(Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_DOWNLOADS), "foo.txt");

try {
    String exampleString = "bar\nfoo";
    InputStream is = new ByteArrayInputStream(exampleString.getBytes(Charset.forName("UTF-8")));
    OutputStream os = new FileOutputStream(file);
    byte[] data = new byte[is.available()];
    is.read(data);
    os.write(data);
    is.close();
    os.close();
} catch (IOException e) {
    throw new AssertionError(e.toString());
}

MediaScannerConnection.scanFile(
        getContext(),
        new String[]{file.getAbsolutePath()},
        null,
        new MediaScannerConnection.OnScanCompletedListener() {
            @Override
            public void onScanCompleted(String s, Uri uri) {
                Log.d(TAG, "String: "+ s);
                Log.d(TAG, "Uri: "+ uri );
            }
        });

它会在onScanCompleted中记录此内容,因此该文件似乎应显示在Downloads中,但它不会显示。

D/SignupFragment: String: /storage/emulated/0/Download/foo.txt
D/SignupFragment: Uri: content://media/external/file/84691

我已阅读Android docs on saving files

的AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

1 个答案:

答案 0 :(得分:1)

标准AOSP下载应用仅显示DownloadManager下载的内容。它不会通过其他方式显示放置在Downloads/目录中的文件。