在 JAVA 中保存 h264 文件有效,但在 android 中保存损坏的文件
saving h264 file in JAVA works, but in android it saves corrupted file
我正在尝试将 h264 格式的字节流保存到 h264 文件中。
我在 JAVA 中完成了,文件正在保存中,我可以打开它并观看视频。
但是,当我在 android 中尝试完全相同的代码并尝试通过 android 设备保存文件时,文件已损坏。
这是我的代码(android 和 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();
}
}
- 当然只是 java 和 android 版本
中的路径不同
可能因为 my_stream.toByteArray() 只是整个视频的一部分。循环读取视频流,逐块写入输出流。
或者,这个功能可以为您完成:
Files.copy(videoInputStream, filePath, StandardCopyOptions.REPLACE_EXISTING);
或者如果输入是字节数组:
Files.write(outputPath, bytes, StandardOpenOptions.WRITE,
StandardOpenOptions.CREATE_NEW,
StandardOpenOptions.CREATE);
https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html
我正在尝试将 h264 格式的字节流保存到 h264 文件中。 我在 JAVA 中完成了,文件正在保存中,我可以打开它并观看视频。 但是,当我在 android 中尝试完全相同的代码并尝试通过 android 设备保存文件时,文件已损坏。 这是我的代码(android 和 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();
}
}
- 当然只是 java 和 android 版本 中的路径不同
可能因为 my_stream.toByteArray() 只是整个视频的一部分。循环读取视频流,逐块写入输出流。
或者,这个功能可以为您完成:
Files.copy(videoInputStream, filePath, StandardCopyOptions.REPLACE_EXISTING);
或者如果输入是字节数组:
Files.write(outputPath, bytes, StandardOpenOptions.WRITE,
StandardOpenOptions.CREATE_NEW,
StandardOpenOptions.CREATE);
https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html