通过程序从网络上下载文件

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.DataInputStream;
import java.net.URL;
import java.net.URLConnection;

class FileDownloader{

  public static void main(String args[]){
    if (args.length!=2){
      System.out.println(
        "Proper Usage: java FileDownloader RemoteFileURL LocalFileName");
      System.exit(0);
    }

  DataInputStream in=null;
  DataOutputStream out=null;
  FileOutputStream fOut=null;

  try{
    URL remoteFile=new URL(args[0]);
    URLConnection fileStream=remoteFile.openConnection();

    // Open the input streams for the remote file 
    fOut=new FileOutputStream(args[1]);

    // Open the output streams for saving this file on disk
    out=new DataOutputStream(fOut);

    in=new DataInputStream(fileStream.getInputStream());

    // Read the remote on save save the file
    int data;
    while((data=in.read())!=-1){
         fOut.write(data);
    }  
    System.out.println("Download of " + args[0] + " is complete." );   
  } catch (Exception e){
     e.printStackTrace();
  } finally {
     try{
       in.close();
       fOut.flush(); 
       fOut.close();      
     } catch(Exception e){e.printStackTrace();}
     
    }
 }
}

本程序可以从任何未受保护的网页上面下载任何文件(如图片,音乐,二进制文件)到本地。 

例子:下载Yahoo的首页到本地

java FileDownloader http://www.yahoo.com/index.html c:\\temp\\yahoo.html

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值