Search code examples
androidoutputstreamandroid-galleryfileoutputstream

Export internally stored video to the android gallery


I currently have an app that can import videos from the android gallery, make a copy of them, and then delete the old file if the user wants to.

Now, I need the user to be able to reverse that action and transfer the video from the app's internal storage to the android gallery.

Here's what i've tried so far :

        //storage/emulated/0/Pictures -- getPath() of line below
        File androidVidGalleryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

        File hiddenVideo = new File("/data/data/mypackagename/app_vidDir/vid_10.mp4");
        File exportedVid = new File(androidVidGalleryPath.getPath()+"/DesiredAlbumName/"+"DesiredVideoName");

        try {
            FileOutputStream newFile = new FileOutputStream (exportedVid);
            FileInputStream oldFile = new FileInputStream (hiddenVideo);

            // Transfer bytes from in to out
            byte[] buf = new byte[1024]; //this will only read 1KB of data, definitely not enough for an entire video.
            oldFile.read(buf);
            newFile.write(buf, 0, buf.length);
            newFile.flush();
            newFile.close();
            oldFile.close();
        } catch (IOException e) {
            Toast.makeText(getActivity(),"ERROR",Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }

        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(exportedVid.getPath());
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        getActivity().sendBroadcast(mediaScanIntent);

For some reason, nothing happens, other than the warning toast that the try catch caused an IOException.

I'm not sure what's going on, any ideas?


Solution

  • You don't need a while loop, when you write the file.:

    byte[] buf = new byte[1024]; //this will only read 1KB of data, definitely not enough for an entire video.
    oldFile.read(buf);
    newFile.write(buf, 0, buf.length);
    

    After you transfer the video, do this (from here: https://developer.android.com/training/camera/photobasics.html#TaskGallery)

    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(mCurrentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }