我应该使用InputStream或FileInputStream或BufferedInputStream?

时间:2014-09-01 14:22:12

标签: java android download inputstream bufferedinputstream

我从服务器下载了一些pdf和视频文件,为此我使用InputStream来收集响应,但我想知道哪个更适合我的目的InputStream或FileInputStream或BufferedInputStream?

URL u = new URL(fileURL);
      HttpURLConnection c = (HttpURLConnection) u.openConnection();
      c.setRequestMethod("GET");
      c.setDoOutput(true);
      c.connect();
      FileOutputStream f = new FileOutputStream(new File(RootFile, fileName));
      InputStream in = c.getInputStream();

      byte[] buffer = new byte[1024];
      int len1 = 0;

      while ((len1 = in.read(buffer)) > 0) {
        f.write(buffer, 0, len1);
      }
      f.close();

1 个答案:

答案 0 :(得分:0)

我用它来下载视频

void downloadFile(String vidN){
int downloadedSize = 0;
int totalSize = 0;
            try {
                // here vidN is the name of the file like bird.mp4
                // here sitepath is the path of the file
                URL url = new URL(sitepath+vidN);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                urlConnection.setRequestMethod("GET");
                urlConnection.setDoOutput(true);

                //connect
                urlConnection.connect();

                //set the path where we want to save the file 

                String RootDir = Environment.getExternalStorageDirectory()
                        + File.separator + "VideoNR2";
                File RootFile = new File(RootDir);
                RootFile.mkdir();



                //create a new file, to save the downloaded file 
                File file = new File(RootDir,""+vidN);

                FileOutputStream fileOutput = new FileOutputStream(file);

                //Stream used for reading the data from the internet
                InputStream inputStream = urlConnection.getInputStream();

                //this is the total size of the file which we are downloading
                totalSize = urlConnection.getContentLength();


                //create a buffer...
                byte[] buffer = new byte[1024];
                int bufferLength = 0;

                while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                    fileOutput.write(buffer, 0, bufferLength);
                    downloadedSize = bufferLength;
                         }
                //close the output stream when complete //
                fileOutput.close();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            catch (Exception e) {

            }       
        }
相关问题