Download remote files

Original link: http://www.cnblogs.com/mjorcen/p/3780492.html

 

Download remote files

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;

// download file 
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);
        Conn URLConnection = url.openConnection ();
         // get the file name 
        String path = url.getPath ();
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssms");
        String fileName = sdf.format(d) + ".jpg";
        System.out.println ( "File Name:" + fileName);
         // Get the total number of bytes 
        int byteCount = conn.getContentLength ();
         Double len = Double.parseDouble (byteCount + "") / (1024 * 1024 );
        DecimalFormat df = new DecimalFormat("0.##");
        logger.info ( "File Size:" + 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 ( "File Download Start ...." );
         int byteRead = 0 ;
         int byteSum = 0 ;
         the 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 ( "file download is complete!" );
         return fileName;
    }
}

 

 

 

 

 

 

 

Reproduced in: https: //www.cnblogs.com/mjorcen/p/3780492.html

Guess you like

Origin blog.csdn.net/weixin_30815469/article/details/94784576