如何从网络下载文件到本地

public class FileDownload {

    /**

     * 下载文件并保存到本地

     *

     * @param url

     *            文件在网络上的路径

     * @param savePath

     *            本地保存路径

   

     */

    public static boolean download(String url, String savePath) {

        boolean result = false;

        File file = FileUtils.getFile(savePath);

        InputStream in = null;

        FileOutputStream fout = null;

        try {

            URL u = new URL(url);// 获得被下载文件的路径

            in = u.openStream();// 打开到此 URL的连接并返回一个用于从该连接读入的 InputStream。

            fout = new FileOutputStream(file);// 生成文件输出流

            byte[] buffer = new byte[CommonContexts.fileBuffer];// 写文件时的缓冲区

            int byteRead = 0;

            while ((byteRead = in.read(buffer)) > 0) {

                fout.write(buffer, 0, byteRead);

            }

            result = true;

        } catch (Exception e) {

            LoggerUtils.error(FileDownload.class.getName(), "从(" + url + ")下载文件并保存到(" + savePath + ")时出错", e);

         

        } finally {

            try {

                if (in != null) {

                    in.close();

                }

                if (fout != null) {

                    fout.flush();

                    fout.close();

                }

            } catch (Exception e) {

                FileUtils.delete(file);

            }

        }

        return result;

    }

    /**

     * 从网络上下载一个文件前面指定字节数的部分

     *

     * @param url

     *            文件在网络上的路径

     * @param byteSize

     *            下载多少个字节

  

     */

    public static byte[] downLoad(String url, int byteSize) {

        byte[] result = new byte[byteSize];

        InputStream in = null;

        try {

            URL u = new URL(url);

            HttpURLConnection connection = (HttpURLConnection) u.openConnection();

            in = connection.getInputStream();

            in.read(result);

        } catch (MalformedURLException e) {

            LoggerUtils.error(FileDownload.class.getName(), "从(" + url + ")下载文件的前" + byteSize + "个字节时出错", e);

        } catch (IOException e) {

            LoggerUtils.error(FileDownload.class.getName(), "从(" + url + ")下载文件的前" + byteSize + "个字节时出错", e);

        } finally {

            try {

                in.close();

            } catch (Exception e) {

            }

        }

        return result;

    }

 

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值