如何从url下载视频文件到SD卡

时间:2011-10-19 17:19:33

标签: android video download sd-card

我正在尝试从真实设备的sd卡中的文件夹中的url下载视频文件而不是在模拟器上。代码是:

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

public class VideoDownload extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    File folder =  new File(Environment.getExternalStorageDirectory()+"/MyFolder");
    folder.mkdir();
    try{ 

    String fileName = Environment.getExternalStorageDirectory()+"/Myfolder";
URL url = new URL("my url/song.mp4");
File file = new File(fileName);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
    }
    catch(Exception e)
    {
    }

    }
    }

我没有收到任何错误,但视频文件未在文件夹中下载。我究竟做错了什么? 任何提示?提前谢谢。

2 个答案:

答案 0 :(得分:1)

尝试以下代码: -

                    try
                    {
                        URL u = new URL(URLS.host_url_main + ce.getString(4));
                        URLConnection ucon = u.openConnection();
                        //Define InputStreams to read from the URLConnection.
                        // uses 3KB download buffer
                        File file =new File(Environment.getExternalStorageDirectory() + "/ptlinkx/"+ce.getString(4).replace("/ExerciseVideo/2/", ""));
                        InputStream is = ucon.getInputStream();
                        BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
                        FileOutputStream outStream = new FileOutputStream(file);
                        byte[] buff = new byte[5 * 1024];

                        //Read bytes (and store them) until there is nothing more to read(-1)
                        int len;
                        while ((len = inStream.read(buff)) != -1)
                        {
                            outStream.write(buff,0,len);
                        }

                        //clean up
                        outStream.flush();
                        outStream.close();
                        inStream.close();
                    }
                    catch (Exception se)
                    {
                         se.printStackTrace();
                    }

答案 1 :(得分:-3)

添加INTERNET使用清单文件中的权限