java從伺服器下載檔案
阿新 • • 發佈:2019-02-17
static public String downloadPrintFile(String filename, String dir) throws IOException {
// 獲取檔案存放路徑
File pf = new File(PrintTask.class.getResource("/").getFile());
String dirPath = pf.getParentFile().getParentFile().getAbsolutePath() + File.separator + dir;
File dirFile = new File(dirPath);
if (!dirFile.exists()) {
dirFile.mkdir();
}
// 檢查檔案檔案
String filePath = dirPath + File.separator + filename;
File file = new File(filePath);
if (!file.exists()) {
// 檔案不存在則下載檔案
String url = TemplateUrl + filename;
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(url);
try {
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode == 200) {
// 得到檔案流
InputStream is = getMethod.getResponseBodyAsStream();
// 建立檔案
file.createNewFile();
// 將得到檔案流輸出到建立的檔案上
FileOutputStream fileout = new FileOutputStream(file);
byte[] buffer = new byte[10240];
int ch = 0;
while ((ch = is.read(buffer)) != -1) {
fileout.write(buffer, 0, ch);
}
is.close();
fileout.flush();
fileout.close();
System.out.println("檔案更新成功:" + file.getName());
return file.getAbsolutePath();
} else {
System.err.println("獲取檔案失敗,statusCode=" + statusCode + ";file=" + url);
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("獲取檔案失敗。file=" + url);
}
} else {
return file.getAbsolutePath();
}
return "";
}
// 獲取檔案存放路徑
File pf = new File(PrintTask.class.getResource("/").getFile());
String dirPath = pf.getParentFile().getParentFile().getAbsolutePath() + File.separator + dir;
File dirFile = new File(dirPath);
if (!dirFile.exists()) {
dirFile.mkdir();
}
// 檢查檔案檔案
String filePath = dirPath + File.separator + filename;
File file = new File(filePath);
if (!file.exists()) {
// 檔案不存在則下載檔案
String url = TemplateUrl + filename;
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(url);
try {
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode == 200) {
// 得到檔案流
InputStream is = getMethod.getResponseBodyAsStream();
// 建立檔案
file.createNewFile();
// 將得到檔案流輸出到建立的檔案上
FileOutputStream fileout = new FileOutputStream(file);
byte[] buffer = new byte[10240];
int ch = 0;
while ((ch = is.read(buffer)) != -1) {
fileout.write(buffer, 0, ch);
}
is.close();
fileout.flush();
fileout.close();
System.out.println("檔案更新成功:" + file.getName());
return file.getAbsolutePath();
} else {
System.err.println("獲取檔案失敗,statusCode=" + statusCode + ";file=" + url);
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("獲取檔案失敗。file=" + url);
}
} else {
return file.getAbsolutePath();
}
return "";
}