如何在内部存储器中创建自定义目录以保存下载的文件?

时间:2019-01-14 06:13:33

标签: android firebase firebase-storage android-internal-storage

我正在使用Firebase开发应用程序。我已将pdf文件手动上传到Firebase存储中,以便用户可以使用该应用下载它。下载的文件存储在 Android->数据-> FileName->目录->文件中。但是我需要一个自定义目录,以将文件直接保存在内部存储中。

   public void downloadFile(){
        str = FirebaseStorage.getInstance().getReference();
        final File mydir = this.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir;

    ref = str.child("AI (presentation).pptx");
        ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                String url = uri.toString();
                downloadFiles(MainActivity.this,"AI",".ppt",mydir ,url);
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {

            }
        });
}

public void downloadFiles(Context context, String fileName, String fileExtension, File destinationDirectory, String url) {

    DownloadManager downloadmanager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    Uri uri = Uri.parse(url);
    DownloadManager.Request request = new DownloadManager.Request(uri);

    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDestinationInExternalFilesDir(context, "" + destinationDirectory, fileName + fileExtension);

    downloadmanager.enqueue(request);
}

1 个答案:

答案 0 :(得分:0)

您不需要使用DownloadManager。 相反,您可以使用StorageReferenece.getBytes()并手动保存文件。

    private static final long DOWNLOAD_LIMIT = 1024 * 1024; // you can change this

    public void downloadFile(){
        StorageReference ref = FirebaseStorage.getInstance().getReference("AI (presentation).pptx");
        ref.getBytes(DOWNLOAD_LIMIT).addOnSuccessListener(new OnSuccessListener<byte[]>() 
        {
            @Override
            public void onSuccess(byte[] bytes) {
                final String path = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/mydir/AI (presentation).pptx";
                try {
                    writeToFile(bytes, path);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                Log.e(TAG, "fail to download: " + exception);
            }
        });
    }

    public void writeToFile(byte[] data, String fileName) throws IOException{
        FileOutputStream out = new FileOutputStream(fileName);
        out.write(data);
        out.close();
    }
相关问题