欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-06-10 11:49:47
...
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

 

相关标签: java 下载