import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class FileDownload {
/**
* 特殊处理含中文的文件名
* @param urlPath
* @param downloadDir
* @return
*/
public static File download(String urlPath, String downloadDir) {
File file = null;
try {
String[] array=urlPath.split("/");
String name=array[array.length-1];
String domain=array[0]+"//"+array[2]+"/";
String dir="";
for(int i=3;i<array.length-1;i++) {
dir+=array[i]+"/";
}
//System.out.println(domain+dir+URLEncoder.encode(name,"UTF-8"));
// 统一资源
URL url = new URL(domain+dir+URLEncoder.encode(name,"UTF-8"));
// http的连接类
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
// 设定请求的方法,默认是GET
connection.setRequestMethod("GET");
// 设置字符编码
connection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)
connection.connect();
int code = connection.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
System.out.println("错误返回码:"+code);
return null;
}
BufferedInputStream bin = new BufferedInputStream(connection.getInputStream());
String path = downloadDir + File.separatorChar + dir+name;
file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(file);
int size = 0;
int len = 0;
byte[] buf = new byte[1024];
while ((size = bin.read(buf)) != -1) {
len += size;
out.write(buf, 0, size);
}
System.out.println("文件下载结束!");
bin.close();
out.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return file;
}
public static void main(String[] args) throws Exception{
//FileDownload.download("http://hadoop.apache.org/images/hadoop-logo.jpg","d:\\download");
//FileDownload.download("http://19912.xc.cangpie.com/xiaz/hadoop实战第3版pdf中文版@68_134529.exe","d:\\download");
}
}