zoukankan      html  css  js  c++  java
  • 下载远程文件

    下载远程文件

    package com.sd.microMsg.util;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.net.URI;
    import java.net.URL;
    import java.net.URLConnection;
    import java.text.DecimalFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import org.apache.log4j.Logger;
    
    // 下载文件
    public class RemoteUtil {
        static Logger logger = Logger.getLogger(RemoteUtil.class);
    
        public static String doGetFile(String URL, String filePath)
                throws Exception {
    
            URL fileUrl = RemoteUtil.class.getClassLoader().getResource(
                    "../../../" + filePath);
            File file = new File(fileUrl.toURI());
            if (!file.exists()) {
                file.mkdirs();
            }
            URL url = new URL(URL);
            URLConnection conn = url.openConnection();
            // 获取文件名
            String path = url.getPath();
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssms");
            String fileName = sdf.format(d) + ".jpg";
            System.out.println("文件名称:" + fileName);
            // 获取总字节数
            int byteCount = conn.getContentLength();
            double len = Double.parseDouble(byteCount + "") / (1024 * 1024);
            DecimalFormat df = new DecimalFormat("0.##");
            logger.info("文件大小:" + df.format(len) + "MB");
    
            InputStream inStream = conn.getInputStream();
            String newFile = fileUrl + fileName;
            File file2 = new File(new URI(newFile));
            FileOutputStream fs = new FileOutputStream(file2);
            byte[] buffer = new byte[1204];
            logger.info("文件开始下载....");
            int byteRead = 0;
            int byteSum = 0;
            while ((byteRead = inStream.read(buffer)) != -1) {
                byteSum += byteRead;
                int num = byteSum * 100 / Integer.parseInt(byteCount + "");
                // System.out.println("已下载" + num + "%....");
                fs.write(buffer, 0, byteRead);
            }
            logger.info("文件下载完成!");
            return fileName;
        }
    }
  • 相关阅读:
    c# 键值数据保存XML文件
    c# 封装 Request操作类
    c# 获取客户端IP
    c#封装DBHelper类
    c# Cache 使用实例
    c#cookie读取写入操作
    c# Session写入读取操作
    ABAP-HTTP支持
    WDA-文档-基础篇/进阶篇/讨论篇
    UI5-文档-4.38-Accessibility
  • 原文地址:https://www.cnblogs.com/mjorcen/p/3780492.html
Copyright © 2011-2022 走看看