</pre><pre name="code" class="java">
使用JavaIO提供的API下载指定文件(image)
package com.net.download;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* ClassName:Test.java
* @author xg.qiu
* @since JDK1.7
* Aug 26, 2015
* 使用JavaIO提供的API下载指定文件(image)
*/
public class DownLoad {
public static void main(String[] args) {
// 调用封装好的方法
download("http://static.oschina.net/uploads/user/500/1000631_50.jpg", "E:/download.jpg");
}
/**
* 封装了用户传参的方法
* @author xg.qiu<br/>
* @since JDK 1.7
* @time Aug 31, 2015
* @param imgUrl 网络上的图片路径地址
* @param newImg 保存在本机上的图片路径地址
*/
public static void download(String imgUrl,String newImg){
try {
//1.创建一个URL
URL url = new URL(imgUrl);
//2.使用数据输入流获取URL信息
DataInputStream data = new DataInputStream(url.openStream());
int dataLength = data.available();
//3.创建一个文件输出流,将网络流输出到文件流
File newFile = new File(newImg);
FileOutputStream output = new FileOutputStream(newFile);
byte [] buffer = new byte[1024];
int len;
// 4.循环读取并写入文件流
while((len = data.read(buffer)) != -1 ){
output.write(buffer,0,len);
}
//关闭网络流
data.close();
//关闭文件流
output.close();
if(newFile.length() == dataLength){
System.out.println("文件下载成功.");
}else{
System.out.println("文件下载失败.");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}