随笔 - 3, 文章 - 0, 评论 - 9, 引用 - 0
数据加载中……

java应用程序从网上下载文件

java应用程序与网络通讯一直是我的弱项,想补一补,就从这一篇开始吧!
以从网上下载一个图象为例:

import  java.io.BufferedInputStream;
import  java.io.BufferedOutputStream;
import  java.io.File;
import  java.io.FileOutputStream;
import  java.io.IOException;
import  java.net.URL;
import  java.net.URLConnection;

public   class  DownloadFormURL {

    
public   static   void  main(String[] args) {
        
try  {
            
new  DownloadFormURL().downloadFile( " http://127.0.0.1:8080/image/f.jpg " new  File( " F:/image.jpg " ));
        } 
catch  (IOException e) {
            e.printStackTrace();
        }
    }

    
public   void  downloadFile(String sourceURL, File targetFile)  throws  IOException {

        URL url 
=   new  URL(sourceURL);
        URLConnection connection 
=  url.openConnection();
        java.io.InputStream inputStream 
=  connection.getInputStream();
        FileOutputStream outputStream 
=   new  FileOutputStream(targetFile);
        BufferedInputStream in 
=   null ;
        BufferedOutputStream out 
=   null ;
        
byte  buffer[]  =   new   byte [ 8192 ];
        
try  {
            in 
=   new  BufferedInputStream(inputStream, buffer.length);
            out 
=   new  BufferedOutputStream(outputStream, buffer.length);
            
int  total  =   0 ;
            
for  ( int  bytesRead  =   0 ; (bytesRead  =  in.read(buffer))  !=   - 1 ;) {
                out.write(buffer, 
0 , bytesRead);
                total 
+=  bytesRead;
            }

        } 
finally  {
            in.close();
            out.close();
        }
        
return ;
    }
}


小试了一下,还不错!

posted on 2006-08-14 09:03 nick 阅读(1702) 评论(6)  编辑  收藏 所属分类: java基础

评论

# re: java应用程序从网上下载文件  回复  更多评论   

<script>alert("hello")</script>
2006-09-07 10:08 | aa

# re: java应用程序从网上下载文件  回复  更多评论   

<script>document.title("hello world")</script>
2006-09-07 10:11 | aa

# re: java应用程序从网上下载文件  回复  更多评论   

xiexie
2006-10-02 09:54 | kk

# re: java应用程序从网上下载文件  回复  更多评论   

安全可靠
2006-11-01 19:05 |

# re: java应用程序从网上下载文件  回复  更多评论   

奶奶内
2006-12-02 20:31 | 奶奶内

# re: java应用程序从网上下载文件  回复  更多评论   

xiexieni
2006-12-12 20:27 | sunxiuqi

只有注册用户登录后才能发表评论。


网站导航: