Android : Copy RawFile to Sdcard (video mp4)

12,036

Solution 1

If you use an InputStream to read, use an OutputStream to write, i.e. a BufferedOutputStream-wrapped FileOutputStream. Also, your code is pretty inefficient, as it only copies one byte at a time. I'd suggest creating a byte array buffer and using these relevant read/write methods:

int BufferedInputStream.read(byte[] buffer, int offset, int length)
void BufferedOutputStream.write(byte[] buffer, int offset, int length)

Solution 2

It works,thanks

BufferedOutputStream bufEcrivain = new BufferedOutputStream((new FileOutputStream(f)));
BufferedInputStream VideoReader = new BufferedInputStream(getResources().openRawResource(R.raw.blow));
byte[] buff = new byte[32 * 1024];
int len;
while( (len = VideoReader.read(buff)) > 0 ){
    bufEcrivain.write(buff,0,len);
}
bufEcrivain.flush();
bufEcrivain.close();

Solution 3

I think you should flush before you close the stream

bufEcrivain.flush();
bufEcrivain.close();
Share:
12,036
NicoMinsk
Author by

NicoMinsk

Avec plus de 15 ans d'expérience dans l'IT, je suis fier de travailler comme CTO chez Kang, où je dirige une équipe de six développeurs, créant des fonctionnalités uniques.🚀 Mon rôle de Leader est d'aider, de motiver, de faire progresser mon équipe pour accomplir de nouveau défi chaque Jour ! Si vous aussi, vous êtes Fan de Laravel & de PHP, n'hésitez pas à me contacter & pourquoi pas nous rejoindre !

Updated on June 04, 2022

Comments

  • NicoMinsk
    NicoMinsk almost 2 years

    What is wrong on this code ?
    I've a Raw file in my project (mp4 videofile),
    when i do this, and then i retreive file from SDcard file are not identical so video can not be load :(
    Do you have another way to automaticly copy a raw file to sdcard ?
    Thanks

    String FICHIER_BLOW = "blowvid4.mp4";
    File f=new File(Environment.getExternalStorageDirectory(), FICHIER_BLOW);
    try {
        if (f.createNewFile()){
        FileWriter ecrivain = new FileWriter(f);
        BufferedWriter bufEcrivain = new BufferedWriter(ecrivain);
        BufferedInputStream VideoReader = new BufferedInputStream(getResources().openRawResource(R.raw.blow));
        while( VideoReader.available() > 0 ){
            bufEcrivain.write(VideoReader.read());
        }
        bufEcrivain.close();
    
        VideoView videoView = (VideoView) findViewById(R.id.VideoView);
        MediaController mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        video =Uri.fromFile(f);
        videoView.setMediaController(mediaController);
        videoView.setVideoURI(video);
        videoView.start();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }