[英]java code to download a file from server
在Windows中使用java代碼我需要從放在服務器中的目錄下載幾個文件。 服務器中的那些文件是單獨生成的。 所以我不知道那些文件的名稱。 有沒有辦法使用JAVA下載它並將其保存在特定的文件夾中。
我正在使用apache tomcat。
我閱讀了與java文件下載相關的所有其他線程。 但它們都不符合我的要求。
try {
// Get the directory and iterate them to get file by file...
File file = new File(fileName);
if (!file.exists()) {
context.addMessage(new ErrorMessage("msg.file.notdownloaded"));
context.setForwardName("failure");
} else {
response.setContentType("APPLICATION/DOWNLOAD");
response.setHeader("Content-Disposition", "attachment"+
"filename=" + file.getName());
stream = new FileInputStream(file);
response.setContentLength(stream.available());
OutputStream os = response.getOutputStream();
os.close();
response.flushBuffer();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
希望你有所了解......
您好,您可以使用以下代碼片段直接下載文件:
URL oracle = new URL("http://www.example.com/file/download?");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
請參考[URL]中的openStream: http ://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html
您可以使用HttpURLConnection
通過HTTP,HTTPS下載文件
使用java.net.URL
和java.net.URLConnection
類。
如果它是服務器,則該過程必須類似於使用您必須加載文件的FTP憑據。 這個java文件下載示例可能對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.