HttpURLConnection从链接下载数据存放本地临时文件,Java
  TEZNKK3IfmPf 2024年07月27日 37 0

HttpURLConnection从链接下载数据存放本地临时文件,Java

    private File download(String url) throws Exception {
        HttpURLConnection connection = getConnection(url);

        int contentLength = connection.getContentLength();

        String msg = connection.getResponseMessage();
        System.out.println(msg);

        InputStream is = connection.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        File tempFile = File.createTempFile(UUID.randomUUID().toString(), "");
        FileOutputStream fos = new FileOutputStream(tempFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        int c;
        int count = 0;
        byte[] buf = new byte[1024 * 4];
        double pcent;
        while (true) {
            c = bis.read(buf);
            if (c == -1)
                break;
            bos.write(buf, 0, c);

            count = count + c;

            pcent = (count / (double) contentLength) * 100;
            System.out.print("已下载:" + String.format("%.2f", pcent) + "% \r");
        }

        bis.close();
        bos.close();
        fos.close();

        return tempFile;
    }

    private HttpURLConnection getConnection(String u) throws Exception {
        URL url = new URL(u);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.connect();

        return connection;
    }
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年07月27日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   10天前   18   0   0 编程开发
  TEZNKK3IfmPf   10天前   16   0   0 编程开发
  TEZNKK3IfmPf   10天前   20   0   0 编程开发i++
  TEZNKK3IfmPf   10天前   22   0   0 编程开发
  I7JaHrFMuDsU   2024年08月09日   77   0   0 javalinux
TEZNKK3IfmPf