在 Windows 中使用 java 代码我需要从放置在服务器中的目录下载几个文件。服务器中的那些文件是单独生成的。所以我不知道这些文件的名称。有什么方法可以使用 JAVA 下载它并将其保存在特定文件夹中。
我正在使用apache tomcat。
我阅读了与 java 文件下载相关的所有其他线程。但没有一个能满足我的要求。
在 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();
}
}
}
希望你有一些想法...
使用java.net.URL
和java.net.URLConnection
类。
您可以使用HttpURLConnection
通过 HTTP、HTTPS 下载文件
仅当服务器列出目录内容时才有可能。如果是这样,您可以向以下位置发出 HTTP 请求:
这会给你文件列表。
一旦你有了它,你可以通过解析这个 http 请求的输出来下载单个文件。
您好,您可以使用以下代码片段直接下载文件:
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
如果它是服务器,则该过程必须像使用 FTP 凭据一样,您必须对文件进行 dosnload。这个java 文件下载示例可能会对您有所帮助。