下载远程文件

 

下载远程文件

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;
    }
}

 

 

 

 

 

 

 

posted @ 2014-06-10 18:06  mjorcen  阅读(225)  评论(0编辑  收藏  举报