如何通过java程序去下载文件

来源:互联网 发布:激光切割排版编程 编辑:程序博客网 时间:2024/05/17 01:45
   
如何通过java程序去下载文件
如何通过java程序去远端下载文件呢?比如用户给你一个地址,让你去下载文件,怎么做呢?下面模拟一个例子。
假设:用户给你的地址是http://localhost:8080/ICCardQueryR2003-02-01.zip
1、一般的下载
我们在java的main方法里写这么段代码
 // 定义httpURLConnection ,初始为null
        HttpURLConnection hc = null;

        
try {
            
// 打开一个http连接
            URL url = new URL(
                    
"http://localhost:8080/ICCardQueryR2003-02-01.zip");
            hc 
= (HttpURLConnection) url.openConnection();

            
// 定义输入流
            InputStream instream = hc.getInputStream();

            
// 创建这个文件输出流
            String tempFileName = "1.zip";
            FileOutputStream fos 
= new FileOutputStream(tempFileName);

            
// 定义一个大小为1024的字节数组
            byte[] buf = new byte[1024];

            
// 从输入流中读出字节到定义的字节数组
            int len = instream.read(buf, 01024);

            
// 循环读入字节,然后写到文件输出流中
            while (len != -1{
                fos.write(buf, 
0, len);
                len 
= instream.read(buf, 01024);

            }

            fos.flush();
            fos.close();

        }
 catch (Exception e) {
            System.err.println(
"下载出错!");

        }
 finally {
            
if (hc != null)
                hc.disconnect();
        }

   
上面这段代码是能够该文件的下载的。这里我们假设的这个url http://localhost:8080/ICCardQueryR2003-02-01.zip 比较特殊,我们这里用的tomact,这个文件要放在webapp下面的root 根目录下面。在现实的应用当中,用户可能给你一个包含jsp或者servlet的地址,但是这个你放心,用户到后来一般会给你文件的,有些是通过转向,有的是通过直接给你输入流。
   写到了这里,我们是不是会问,如果我们下了一会没完全下来怎么办呢,那我们要写一个能支持断点续传的类,如下面代码。
2、支持断点续传的下载
   /**
     * 
@param args
     * 
@throws IOException
     
*/

    
public static void main(String[] args) throws IOException {
        
// 定义httpURLConnection ,初始为null
        HttpURLConnection hc = null;
        URL url 
= null;
        String tempFileName 
= "1.zip";
        String sUrl 
= "http://localhost:8080/ICCardQueryR2003-02-01.zip";

        
long beginPos = 0;
        
long fileLength = 0;
        
int num = 0;
        
boolean isFinish = false;
        
boolean isFirst = true;
        
while (!isFinish && num <= 3{
            
try {
                url 
= new URL(sUrl);
                hc 
= (HttpURLConnection) url.openConnection();
                
// 定义从beginPos位置处开始
                hc.setRequestProperty("User-Agent""Java/1.4.2");
                hc.setRequestProperty(
"RANGE""bytes="
                        
+ String.valueOf(beginPos) + "-");
                
// 定义输入流
                InputStream instream = hc.getInputStream();

                
if (isFirst) {
                    fileLength 
= getFileLength(hc);
                    isFirst 
= false;
                }


                
// 创建这个文件输出流
                RandomAccessFile ras = new RandomAccessFile(tempFileName, "rw");
                ras.seek(beginPos);

                
// 定义一个大小为1024的字节数组
                byte[] buf = new byte[1024];

                
int len = instream.read(buf, 01024);

                
// 循环读入字节,然后写到文件输出流中
                while (len > 0{
                    beginPos 
+= len;
                    ras.write(buf, 
0, len);
                    len 
= instream.read(buf, 01024);
                }


                ras.close();
                
if (beginPos >= fileLength) {
                    isFinish 
= true;
                }


            }
 catch (MalformedURLException e) {
                System.err.println(e.getMessage());
            }
 catch (IOException e) {
                System.err.println(e.getMessage());
            }
 finally {
                num
++;
                hc.disconnect();
            }

        }


    }


    
/**
     * 从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;
    }

原创粉丝点击