通过程序从网络上下载文件
程序员文章站
2022-06-10 11:23:22
...
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