簡體   English   中英

Android - 如何使用新的存儲訪問框架將文件復制到外部SD卡

[英]Android - How to use new Storage Access Framework to copy files to external sd card

我正在我的應用程序中實現文件瀏覽器功能。 我知道如何使用ACTION_OPEN_DOCUMENT_TREE意圖獲得外部SD卡的持久權限,以及如何使用DocumentFile類創建文件夾和刪除文件/文件夾。

但是,我找不到將文件復制/移動到外部SD卡文件夾的方法。 你能指出我正確的方向嗎?

我已經在SO上使用了很多例子。 我的音樂文件解決方案:

     private String copyFile(String inputPath, String inputFile, Uri treeUri) {
    InputStream in = null;
    OutputStream out = null;
    String error = null;
    DocumentFile pickedDir = DocumentFile.fromTreeUri(getActivity(), treeUri);
    String extension = inputFile.substring(inputFile.lastIndexOf(".")+1,inputFile.length());

    try {
        DocumentFile newFile = pickedDir.createFile("audio/"+extension, inputFile);
        out = getActivity().getContentResolver().openOutputStream(newFile.getUri());
        in = new FileInputStream(inputPath + inputFile);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        // write the output file (You have now copied the file)
        out.flush();
        out.close();

    } catch (FileNotFoundException fnfe1) {
        error = fnfe1.getMessage();
    } catch (Exception e) {
        error = e.getMessage();
    }
    return error;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM