一个通过流形式下载文件,可下载各种文件……以供学习交流
/**
* 文件下载方法p
* @param fUrl 源文件地址 如:http://a.html
* @param sUrl 保存地址 如:D://
* @return
*/
public boolean DownFile(String fUrl,String sUrl){
String[] urlname = fUrl.split("/");
int len = urlname.length-1;
String uname = urlname[len];//获取文件名
try {
File file = new File(sUrl+uname);//创建新文件
if(file!=null && !file.exists()){
file.createNewFile();
}
OutputStream oputstream = new FileOutputStream(file);
URL url = new URL(fUrl);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.setDoInput(true);//设置是否要从 URL 连接读取数据,默认为true
uc.connect();
InputStream iputstream = uc.getInputStream();
System.out.println("file size is:"+uc.getContentLength());//打印文件长度
byte[] buffer = new byte[4*1024];
int byteRead = -1;
while((byteRead=(iputstream.read(buffer)))!= -1){
oputstream.write(buffer, 0, byteRead);
}
oputstream.flush();
iputstream.close();
oputstream.close();
System.out.println("源文件:"+fUrl);
System.out.println("下载到:"+sUrl+uname);
return true;
} catch (Exception e) {
System.out.println("下载失败!");
e.printStackTrace();
return false;
}
}