Finer
Finer

Reputation: 19

saving h264 file in JAVA works, but in android it saves corrupted file

I am trying to save a stream of bytes in h264 format, to an h264 file. I did it in JAVA, and the file is being saved and I can open it and see the video. BUT, when I try the exact same code, in android, and I'm trying to save the file through the android device, the file is corrupted. This is my code (both for android and for java):

    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
    File file = new File(path, "/" + "filename2.mp4");
    FileOutputStream output2 = null;
    try {
        output2 = new FileOutputStream(file, true);
        output2.write(my_stream.toByteArray());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            output2.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Upvotes: 0

Views: 272

Answers (1)

zjmo
zjmo

Reputation: 675

Maybe because my_stream.toByteArray() is only one part of the whole video. Read the video stream in a loop and write it to the output stream chunk by chunk.

Alternatively there is this function that will do it for you:

Files.copy(videoInputStream, filePath, StandardCopyOptions.REPLACE_EXISTING);

Or if the input is a byte array:

Files.write(outputPath, bytes, StandardOpenOptions.WRITE, 
    StandardOpenOptions.CREATE_NEW, 
    StandardOpenOptions.CREATE);

Full documentation: https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#write(java.nio.file.Path,%20byte[],%20java.nio.file.OpenOption...)

https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html

Upvotes: 2

Related Questions