从web工程中下载文件到本地硬盘

来源:互联网 发布:linux操作系统有什么用 编辑:程序博客网 时间:2024/06/05 15:25
package com.web;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
 * <文件下载,从web工程中下载文件到本地硬盘>
 * <功能详细描述>
 *
 * @author  Vincent
 * @version  [版本号, 2014-10-10]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class HttpDownLoadUtil
{
    /**
     * 文件下载
     *
     * @param sUrl
     * @throws IOException
     */
    public static String httpDownLoad(String sUrl, String localPath, String newFileName)
        throws IOException
    {
        // 定义httpURLConnection ,初始为null
        HttpURLConnection hc = null;
        
        URL url = null;
        
        long beginPos = 0;
        
        long fileLength = 0;
        
        RandomAccessFile ras = null;
        
        String fileName = getFileName(sUrl);
        String tempFileName = null;
        if (sUrl == null && "".equals(sUrl))
        {
            return null;
        }
        else
        {
            tempFileName = localPath + newFileName;
        }
        
        try
        {
            url = new URL(sUrl);
            hc = (HttpURLConnection)url.openConnection();
            File file = new File(tempFileName);

          //注释判断是否已经存在。使能够覆盖原来存在图片

//            if (file.exists())
//            {
//                beginPos = file.length();
//            }

            // 定义从beginPos位置处开始
            hc.setRequestProperty("User-Agent", "HttpDownLoadUtil");
            hc.setRequestProperty("RANGE", "bytes=" + String.valueOf(beginPos) + "-");
            
            fileLength = getFileLength(hc);
            
            // 可能已下完文件,所以这里需要判断下
            if (beginPos >= fileLength)
            {
                return fileName;
            }
            
            // 定义输入流
            InputStream instream = hc.getInputStream();
            ras = new RandomAccessFile(file, "rw");
            ras.seek(beginPos);
            
            // 定义一个大小为1024的字节数组
            byte[] buf = new byte[1024];
            
            int len = instream.read(buf, 0, 1024);
            
            // 循环读入字节,然后写到文件输出流中
            while (len > 0)
            {
                beginPos += len;
                ras.write(buf, 0, len);
                len = instream.read(buf, 0, 1024);
            }
            if (beginPos >= fileLength)
            {
                return fileName;
            }
        }
        catch (MalformedURLException e)
        {
            System.err.println(e.getMessage());
        }
        catch (IOException e)
        {
            System.err.println(e.getMessage());
        }
        finally
        {
            if (hc != null)
            {
                hc.disconnect();
            }
            if (ras != null)
            {
                ras.close();
            }
        }
        return null;
    }
    
    /**
     * 从HttpURLConnection中得到文件长度,此HttpURLConnection为已经开启连接后的状态
     *
     * @param hc
     * @return long
     */
    private static long getFileLength(HttpURLConnection hc)
    {
        long nFileLength = -1;
        for (int i = 1;; i++)
        {
            String sHeader = hc.getHeaderFieldKey(i);
            if (sHeader != null)
            {
                if (sHeader.equals("Content-Length"))
                {
                    nFileLength = Long.parseLong(hc.getHeaderField(sHeader));
                    break;
                }
            }
            else
            {
                break;
            }
        }
        
        return nFileLength;
    }
    
    /**
     * 获取url链接的文件名称
     *
     * @param url
     * @return
     */
    public static String getFileName(String url)
    {
        String fileName = null;
        if (url != null && !"".equals(url))
        {
            fileName = url.substring(url.lastIndexOf("/") + 1);
        }
        return fileName;
    }
    
    public static void main(String args[])
        throws IOException

    {
        String src = "http://192.168.102.52:8080/TestWeb/image/default/default.jpg";
        String dst="E:/mypic/cc.jpg";
        String fileName="";
        String dst2="E:/mypic/";
        String fileName2="cc.jpg";
        httpDownLoad(src, dst,fileName);
    }
    
}

0 0
原创粉丝点击