1. 程式人生 > >Java從web伺服器下載檔案到本地

Java從web伺服器下載檔案到本地

/*從伺服器中下載檔案到本地*/
/*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 "";
}