2011-03-17 82 views
5

在Windows中使用java代碼我需要從放置在服務器中的目錄下載幾個文件。服務器中的這些文件是分開生成的。所以我不會知道這些文件的名稱。有什麼方法可以使用JAVA下載並將其保存在特定的文件夾中。從服務器下載文件的java代碼

我使用的是Apache Tomcat。

我讀了所有其他與java文件下載相關的線程。但他們都不符合我的要求。

回答

2

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

2

只有當服務器列出目錄內容時纔有可能。如果是這樣,你可以使一個HTTP請求:

http://server:port/folder

,會給你的文件列表。

一旦你有了,你可以通過解析輸出來下載單個文件,如果這個http請求。

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

希望你有一些想法...

2

嗨,你可以使用這個下面的代碼段向下直接文件:

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

請參閱有關的OpenStream在這個[URL]:http://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html