一个简单的 java 文件流下载函数

时间:2021-04-03 20:51:42

一个简单的 java 流下载函数


import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

  public static void main(String[] args)
  {
    try
    {
      SaveURL("c:/temp/004.pdf", "http://download.localhost/%e5%b0%81%e9%9d%a2.pdf");
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }

  /**
   * 简单文件下载 <br>
   * 下载文件到指定目录
   * 
   * @param filename
   * @param urlString
   * @throws MalformedURLException
   * @throws IOException
   */
  public static void SaveURL(final String strFileName, final String strURL) throws MalformedURLException, IOException
  {
    BufferedInputStream bufferedInputStream = null;
    FileOutputStream fileOutputStream = null;

    int count = -1;
    try
    {
      bufferedInputStream = new BufferedInputStream(new URL(strURL).openStream());
      fileOutputStream = new FileOutputStream(strFileName);
      // InputStream read
      final int buffer = 1024;
      final byte data[] = new byte[buffer];
      while ((count = bufferedInputStream.read(data, 0, buffer)) != -1)
      {
        fileOutputStream.write(data, 0, count);
      }
    }
    catch (Exception e)
    {
    }
    finally
    {
      if (bufferedInputStream != null)
      {
        bufferedInputStream.close();
      }
      if (fileOutputStream != null)
      {
        fileOutputStream.close();
      }
    }
  }


另一个方法,基于 apache httpClient 的:


  /**
   * 
   * @param url
   * @param destFileName
   */
  public Boolean getFile(final String strRemoteFile, String strLocalFile)
  {
    /**
     * http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html<br>
     * 参考
     */

    Boolean result = null;

    try
    {
      // 生成一个httpclient对象
      CloseableHttpClient httpclient = HttpClients.createDefault();
      HttpGet httpget = new HttpGet(strRemoteFile);

      HttpResponse response = httpclient.execute(httpget);
      HttpEntity entity = response.getEntity();

      InputStream inputStream = entity.getContent();
      File file = new File(strLocalFile);
      try
      {
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        int l = -1;
        byte[] tmp = new byte[1024];
        while ((l = inputStream.read(tmp)) != -1)
        {
          fileOutputStream.write(tmp, 0, l);
        }
        fileOutputStream.flush();
        fileOutputStream.close();

        result = true;
      }
      catch (IOException e)
      {
        e.printStackTrace();
        result = false;
      }
      finally
      {
        // 关闭低层流。
        inputStream.close();
      }
      httpclient.close();
    }
    catch (IOException e)
    {
      e.printStackTrace();
      result = false;
    }

    return result;
  }


Q群236201801讨论

.