2009年4月13日 星期一

從網址上下載檔案 by java

使用 URLConnection 就是了

範例碼如下

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



public class DownloadFileFromWeb {
public static void main(String[] args) throws IOException {

BufferedInputStream WebSource = null;

// set source file url
URL sourceFile = new URL("http://sites.google.com/site/catonchuang/Home/Taipei.gif");
// connect
URLConnection con = sourceFile.openConnection();
//System.out.println(con.getContentLength());
//con.connect();
// set Save file buffer
FileOutputStream SaveBuffer = null;
// get file
WebSource = new BufferedInputStream(con.getInputStream());
// set file Position
File FilePosition = new File("C:\\Taipei.gif");
SaveBuffer = new FileOutputStream(FilePosition);

// save into file
byte[] buf = new byte[1024];
int len;
while ((len = WebSource.read(buf)) > 0){
SaveBuffer.write(buf, 0, len);
}
// close buffer
WebSource.close();
SaveBuffer.close();

}

}

沒有留言: