Сохранить видео во внутреннюю память

У меня есть videoView, который воспроизводит видео с пути, соответствующего видеофайлу в галерее Android.

 VideoView videoView1 = (VideoView)promptsView.findViewById(R.id.videoView09);
            String SrcPath = "/storage/emulated/0/DCIM/Camera/20150824_210148.mp4";
            videoView1.setVideoPath(SrcPath);
            videoView1.requestFocus();
            videoView1.start();

Теперь мне нужно каким-то образом сохранить видео из этого видеопросмотра во внутреннюю память для моего приложения.

Мне удалось сделать это для фотографий, используя

public String saveImageToInternalStorage(Bitmap image, String imgRequestedName) {
    ContextWrapper cw = new ContextWrapper(getActivity());
    File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
    File mypath=new File(directory,imgRequestedName+".jpg");
    String loc = mypath.getAbsolutePath();
    FileOutputStream fos = null;
    try {

        fos = new FileOutputStream(mypath);
        image.compress(Bitmap.CompressFormat.JPEG, 70, fos);
        SharedPreferences pref = getActivity().getApplicationContext().getSharedPreferences("MyPref", Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor = pref.edit();
        editor.putInt("totalImageCount",(pref.getInt("totalImageCount",0))+1);
        editor.commit();

        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return mypath.getAbsolutePath();
}

Как я могу сделать эквивалент для видео?

и как я могу прочитать видео с внутренней памяти?


person Zachary Wathen    schedule 26.09.2015    source источник


Ответы (4)


Вот коды для сохранения видео во внутреннюю память для вашего приложения в частном порядке. А также код для чтения видео из внутренней памяти. Надеюсь это поможет.

//For saving Video...

private void saveVideoToInternalStorage (String filePath) {

    File newfile;

    try {

        File currentFile = new File(filePath);
        String fileName = currentFile.getName();

        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        File directory = cw.getDir("videoDir", Context.MODE_PRIVATE);


        newfile = new File(directory, fileName);

        if(currentFile.exists()){

            InputStream in = new FileInputStream(currentFile);
            OutputStream out = new FileOutputStream(newfile);

            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;

            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }

            in.close();
            out.close();

            Log.v("", "Video file saved successfully.");

        }else{
            Log.v("", "Video saving failed. Source file missing.");
        }



    } catch (Exception e) {
        e.printStackTrace();
    }

}

private void loadVideoFromInternalStorage(String filePath){

    Uri uri = Uri.parse(Environment.getExternalStorageDirectory()+filePath);
    myVideoView.setVideoURI(uri);

}
person Oyewo Remi    schedule 27.06.2018

Сохранение видео с использованием его пути во внутреннюю память:

 ContextWrapper cw = new ContextWrapper(getActivity());
 File directory = cw.getDir("vidDir", Context.MODE_PRIVATE);
 File mypath=new File(directory,vidRequestedName+".mp4");

            try {
                FileOutputStream newFile = new FileOutputStream (mypath);
                //path 0 = current path of the video
                FileInputStream oldFile = new FileInputStream (path0);

                // Transfer bytes from in to out
                byte[] buf = new byte[1024];
                int len;
                while ((len = oldFile.read(buf)) > 0) {
                    newFile.write(buf, 0, len);
                }
                newFile.flush();
                newFile.close();
                oldFile.close();
person Zachary Wathen    schedule 26.09.2015

Вы должны использовать uri. В примере я создал «сырой» файл в ресурсах, но вы можете изменить его по своему усмотрению.

Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.example.mp4);
videoView.setVideoURI(uri);
person SedatD    schedule 10.10.2016

Сохранение видео во внутренней памяти с uuid

private void saveVideoToInternalStorage() {
    UUID uuid = UUID.randomUUID();

    try {

        File currentFile = new File(filePath);
        File loc = Environment.getExternalStorageDirectory();
        File directory = new File(loc.getAbsolutePath()+"/FolderNameWhateverYouWant");
        directory.mkdir();
        String fileName = String.format( uuid+".mp4");
        File newfile = new File(directory, fileName);


        if(currentFile.exists()){

            InputStream inputStream = new FileInputStream(currentFile);
            OutputStream outputStream = new FileOutputStream(newfile);

            byte[] buf = new byte[1024];
            int len;

            while ((len = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, len);
            }

            outputStream.flush();
            inputStream.close();
            outputStream.close();

            Toast.makeText(getApplicationContext(),"Video has just saved!!",Toast.LENGTH_LONG).show();

        }else{
            Toast.makeText(getApplicationContext(),"Video has failed for saving!!",Toast.LENGTH_LONG).show();
        }


    } catch (Exception e) {
        e.printStackTrace();
    }

}

Не забудьте запросить разрешение

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
person yusufgltc    schedule 03.09.2020