从网络上下载 文件 图片 视频 压缩包

注:这个是别人用过的  我只不过加了几个例子  整理一下 

1.文件来源地址相应改掉

2.以这个为例,存储路径里必须有 test  这个文件夹   如果没有  加上这一段

File file = new File("E:\\test");
            //如果文件夹不存在  就创建一个空的文件夹
            if (!file.exists()) {
                file.mkdirs();
            }
package IOFile;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * 下载  文件  图片  视频  压缩包
 */
public class DownloadFile {

    public static void main(String[] args) {
        httpDownload("http://192.168.148.140:5080/test.txt", "E:\\test\\test.txt");
        httpDownload("http://192.168.148.140:5080/0ae4d931-1544-4a2b-bb0d-3e2be3b5b926.jpg", "E:\\test\\test.jpg");
        httpDownload("http://192.168.148.140:5080/20181220_133558.avi", "E:\\test\\test.avi");
        httpDownload("http://192.168.148.140:5080/aa.zip", "E:\\test\\test.zip");
    }


    public static boolean httpDownload(String httpUrl, String saveFile) {
        // 1.下载网络文件
        int byteRead;
        URL url;
        try {
            url = new URL(httpUrl);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
            return false;
        }

        try {
            //2.获取链接
            URLConnection conn = url.openConnection();
            //3.输入流
            InputStream inStream = conn.getInputStream();
            //3.写入文件
            FileOutputStream fs = new FileOutputStream(saveFile);

            byte[] buffer = new byte[1024];
            while ((byteRead = inStream.read(buffer)) != -1) {
                fs.write(buffer, 0, byteRead);
            }
            inStream.close();
            fs.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


}

 

原博客链接:https://www.cnblogs.com/IT-study/p/9239717.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值