java Android:将 RawFile 复制到 Sdcard(视频 mp4)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3367894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android : Copy RawFile to Sdcard (video mp4)
提问by NicoMinsk
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
这段代码有什么问题?
我的项目中有一个原始文件(mp4 视频文件),
当我这样做时,然后我从 SDcard 文件中检索文件不相同,因此无法加载视频:(
你有另一种方法可以自动将原始文件复制到sdcard ?
谢谢
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();
}
回答by Roman Nurik
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:
如果使用 InputStream 读取,则使用 OutputStream 写入,即使用 BufferedOutputStream 包装的 FileOutputStream。此外,您的代码效率很低,因为它一次只复制一个字节。我建议创建一个字节数组缓冲区并使用这些相关的读/写方法:
int BufferedInputStream.read(byte[] buffer, int offset, int length)
void BufferedOutputStream.write(byte[] buffer, int offset, int length)
回答by NicoMinsk
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();
回答by softarn
I think you should flush before you close the stream
我认为你应该在关闭流之前冲洗
bufEcrivain.flush();
bufEcrivain.close();

