---
title: "读入一个url,把这个url的文件存到本地硬盘上(类似下载功能)"
author: "hellsing42"
date: "2007-08-21T16:33:07Z"
tags: []
slug: "url-url"
draft: false
lastmod: "2007-08-21T16:33:07Z"
id: 114916
url: "https://hellsing42.iteye.com/blog/114916"
---

加入缓冲后文件正确的代码 


代码

```

    public void downloadLatestVersion(){   
        String downloadURL=this.getLatestVersionURL();   
        try {   
            byte[] buffers=new byte[10240];   
            int size=buffers.length;   
            URL url=new URL(downloadURL);   
            HttpURLConnection conn=(HttpURLConnection) url.openConnection();   
            BufferedInputStream reader=new BufferedInputStream(conn.getInputStream());   
            File dir=new File("D:\\test.jar");   
            FileOutputStream out=new FileOutputStream(dir);   
  
            while((size=reader.read(buffers))>0){   
            out.write(buffers, 0, size);       
}   
            out.flush();   
            reader.close();   
            out.close();   
               
           
  
               
               
               
               
               
               
        } catch (Exception e) {   
            // TODO 自动生成 catch 块   
            e.printStackTrace();   
        }   
           
           
           
  
    }   


```

特别说明下BufferedInputStream.read(byte b)这个值的返回值有俩两个功能: 
1.告诉你这次读入数组用了多少,比如范围为1024的数组,用此方法后返回为456,那就表示他只用了1024里面的前456个,这个值可以用writer方法中,之前出错就是因为没有对这里进行限制,都是存入1024,导致文件出问题的. 
2.如果等于-1表示文件读完了.这个貌似还是有不同理解请看 
http://blog.csdn.net/shendl/archive/2007/03/26/1542126.aspx 
不知道各位觉得比较简单的问题是不会呢还是不屑于回答我