Java从web服务器下载文件到本地

来源:互联网 发布:唐诗三百首详析 淘宝网 编辑:程序博客网 时间:2024/05/17 06:06
 
/*从服务器中下载文件到本地*/
/*url:文件存放在服务器的地址;target:要保存的路径*/
 
public String DownloadFile(String url,String target){
URLConnection con=null;
URL theUrl=null;
try {
theUrl=new URL(url);//建立地址
con = theUrl.openConnection();//打开连接
con.setConnectTimeout(30000);
con.connect();//连接
} catch (MalformedURLException e) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
return "给定的URL地址有误,请查看";
}
catch (IOException e) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
return "无法连接到远程机器,请重试!";
}
jLabel5.setText("√");
Process++;
File file = new File(gbl_ParentPath+"/UpdateTemp");
if(file.exists()==false){
file.mkdir();
}
String type = con.getContentType();
if (type != null) {
byte[] buffer = new byte[4 * 1024];
int read;
try {
FileOutputStream os = new FileOutputStream(target);
InputStream in = con.getInputStream();//重定向输入
while ((read = in.read(buffer)) > 0) {//读取输出
os.write(buffer, 0, read);//写入本地文件
}
os.close();
in.close();
jLabel6.setText("√");
Process++;
} catch (FileNotFoundException e) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
return "所要下载的文件不存在!";
}catch (IOException e) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
return "读取远程文件时出错!";
}
} else {
return "文件未找着:"+url;
}
return "";
}
原创粉丝点击