import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/*
* 下載網絡上的數據(圖片,文件,視頻)
*/
public class DownloadFile
{
public static void download(String urlpath,String filename,String savepath)
{
try {
URL url = new URL(urlpath);
URLConnection conn= url.openConnection();
conn.setConnectTimeout(5000);
InputStream in = conn.getInputStream();
File path = new File(savepath);
if(!path.exists())
{
path.mkdirs();
}
OutputStream out = new FileOutputStream(path.getPath()+"\\"+filename);
int len =0;
byte[] b = new byte[2048];
while((len=in.read(b))!=-1)
{
out.write(b, 0, len);
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
String path ="http://www.verydemo.com/demo_c98_i4648.html";
String filename="myfile.html";
String savepath = "d:/image";
download(path,filename,savepath);
}
}