JAVA实现从URL下载文件

URL下载和服务器下载是不同的,
如果是从服务区上下载,需要提供服务器的文件路径来创建输入流

FileInputStream fileInputStream = new FileInputStream(new File("\User\User.pdf"));

如果是从URL上面下载,则需要提供域名访问地址,通过构建url作为输入流

//构造URL
URL url = new URL("https://downloads.mysql.com/docs/ndb-internals-en.a4.pdf");
URLConnection con = url.openConnection();
con.setConnectTimeout(20 * 1000);
InputStream inputStream = con.getInputStream();

代码示例

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

@Controller
public class Download {

    @RequestMapping("/downloadFile")
    @ResponseBody
    public void downloadFile(HttpServletResponse response) throws IOException {

            //构造URL
            URL url = new URL("https://downloads.mysql.com/docs/ndb-internals-en.a4.pdf");
            URLConnection con = url.openConnection();
            con.setConnectTimeout(20 * 1000);
//
//            FileInputStream fileInputStream = new FileInputStream(new File("d:\\XXX"));
        try {
            // 通过输入流读取文件内容
            InputStream inputStream = con.getInputStream();
            // 指定目的路径,获取到输出流
            File out = new File("D:\\test1");
            if (!out.exists()) {
                out.mkdirs();
            }
            OutputStream outputStream = new FileOutputStream(out.getPath()+"\\"+"1.pdf");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1){
                // 通过输出流,下载到本地
                outputStream.write(bytes,0,len);
//                // 刷新
//                outputStream.flush();
            }

            // 5、关闭资源
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值