АНДРОИД: Как загрузить видеофайл на SD-карту? - PullRequest
16 голосов
/ 11 сентября 2010

У меня есть видеофайл на веб-сайте в формате .MP4, и я хочу позволить пользователю иметь возможность загружать видео на свою SD-карту, нажав ссылку.Есть простой способ сделать это.В настоящее время у меня есть этот код, но он не работает ... не уверен, что я делаю неправильно.Спасибо за любую помощь!

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class VideoManager extends Activity {
 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);}



        private final String PATH = "/sdcard/download/";  //put the downloaded file here


        public void DownloadFromUrl(String VideoURL, String fileName) {  //this is the downloader method
                try {
                        URL url = new URL("http://www.ericmoyer.com/episode1.mp4"); //you can write here any link
                        File file = new File(fileName);

                        long startTime = System.currentTimeMillis();
                        Log.d("VideoManager", "download begining");
                        Log.d("VideoManager", "download url:" + url);
                        Log.d("VideoManager", "downloaded file name:" + fileName);
                        /* Open a connection to that URL. */
                        URLConnection ucon = url.openConnection();

                        /*
                         * Define InputStreams to read from the URLConnection.
                         */
                        InputStream is = ucon.getInputStream();
                        BufferedInputStream bis = new BufferedInputStream(is);

                        /*
                         * Read bytes to the Buffer until there is nothing more to read(-1).
                         */
                        ByteArrayBuffer baf = new ByteArrayBuffer(50);
                        int current = 0;
                        while ((current = bis.read()) != -1) {
                                baf.append((byte) current);
                        }

                        /* Convert the Bytes read to a String. */
                        FileOutputStream fos = new FileOutputStream(PATH+file);
                        fos.write(baf.toByteArray());
                        fos.close();
                        Log.d("VideoManager", "download ready in"
                                        + ((System.currentTimeMillis() - startTime) / 1000)
                                        + " sec");

                } catch (IOException e) {
                        Log.d("VideoManager", "Error: " + e);
                }

        }
}

Ответы [ 2 ]

36 голосов
/ 15 июля 2011

не хватает памяти? Я предполагаю, что видеофайл очень большой - который вы буферизуете перед записью в файл.

Я знаю, что ваш пример кода есть по всему Интернету - но это плохо для загрузки! Используйте это:

private final int TIMEOUT_CONNECTION = 5000;//5sec
private final int TIMEOUT_SOCKET = 30000;//30sec


            URL url = new URL(imageURL);
            long startTime = System.currentTimeMillis();
            Log.i(TAG, "image download beginning: "+imageURL);

            //Open a connection to that URL.
            URLConnection ucon = url.openConnection();

            //this timeout affects how long it takes for the app to realize there's a connection problem
            ucon.setReadTimeout(TIMEOUT_CONNECTION);
            ucon.setConnectTimeout(TIMEOUT_SOCKET);


            //Define InputStreams to read from the URLConnection.
            // uses 3KB download buffer
            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();

            Log.i(TAG, "download completed in "
                    + ((System.currentTimeMillis() - startTime) / 1000)
                    + " sec");5
24 голосов
/ 12 сентября 2010

Никогда не прокладывайте путь, особенно к внешнему хранилищу. Ваш путь неверен на многих устройствах. Используйте Environment.getExternalStoragePath() для получения корня внешнего хранилища (которое может быть /sdcard или /mnt/sdcard или что-то еще).

Обязательно создайте свой подкаталог, используя объект File, который вы получите от Environment.getExternalStoragePath().

И, наконец, не просто говорите "но это не работает". Мы понятия не имеем, что означает «но это не работает» в вашем случае. Без этой информации вам очень трудно помочь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...