Android: save a file from an existing URI

后端 未结 8 962
半阙折子戏
半阙折子戏 2020-12-03 03:39

How to save a media file (say .mp3) from an existing URI, which I am getting from an Implicit Intent?

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 03:53

    When receiving a android.net.Uri from an external source, the best way to save the file is from the stream:

    try (InputStream ins = activity.getContentResolver().openInputStream(source_uri)) {
        File dest = new File(destination_path);
        createFileFromStream(ins, dest);
    } catch (Exception ex) {
        Log.e("Save File", ex.getMessage());
        ex.printStackTrace();
    }
    

    createFileFromStream method:

    public static void createFileFromStream(InputStream ins, File destination) {
        try (OutputStream os = new FileOutputStream(destination)) {
            byte[] buffer = new byte[4096];
            int length;
            while ((length = ins.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
            os.flush();
        } catch (Exception ex) {
            Log.e("Save File", ex.getMessage());
            ex.printStackTrace();
        }
    }
    

提交回复
热议问题