从服务器下载文件的java代码

在Windows中使用java代码我需要从放在服务器中的目录下载几个文件。 服务器中的那些文件是单独生成的。 所以我不知道那些文件的名称。 有没有办法使用JAVA下载它并将其保存在特定的文件夹中。

我正在使用apache tomcat。

我阅读了与java文件下载相关的所有其他线程。 但它们都不符合我的要求。

使用java.net.URLjava.net.URLConnection类。

  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(); } } } 

希望你有所了解……

您可以使用HttpURLConnection通过HTTP,HTTPS下载文件

只有服务器列出目录内容才有可能。 如果是,您可以发出HTTP请求:

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凭据。 这个java文件下载示例可能对您有所帮助。