且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将图像复制到SD卡上的现有目录?

更新时间:2023-02-03 16:02:22

这是我使用SAF完成工作的方式.

This is the way I used SAF to get the job done.

private void newcopyFile(File fileInput, String outputParentPath,
                    String mimeType, String newFileName) {

DocumentFile documentFileGoal = DocumentFile.fromTreeUri(this, treeUri);

String[] parts = outputParentPath.split("\\/");
for (int i = 3; i < parts.length; i++) { //ex: parts:{"", "storage", "extSdCard", "MyFolder", "MyFolder", "MyFolder"}
    if (documentFileGoal != null) {
        documentFileGoal = documentFileGoal.findFile(parts[i]);
    }
}
if (documentFileGoal == null) {
    Toast.makeText(MainActivity.this, "Directory not found", Toast.LENGTH_SHORT).show();
    return;
}

DocumentFile documentFileNewFile = documentFileGoal.createFile(mimeType, newFileName);

InputStream inputStream = null;
OutputStream outputStream = null;
try {
    outputStream = getContentResolver().openOutputStream(documentFileNewFile.getUri());
    inputStream = new FileInputStream(fileInput);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
try {
    if (outputStream != null) {
        byte[] buffer = new byte[1024];
        int read;
        if (inputStream != null) {
            while ((read = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, read);
            }
        }
        if (inputStream != null) {
            inputStream.close();
        }
        inputStream = null;
        outputStream.flush();
        outputStream.close();
        outputStream = null;
    }
} catch (IOException e) {
    e.printStackTrace();
}
}