2016-07-01 34 views
0

我在「localhost:8888/fileserver」有一個靜態文件服務器。 我想在java中編寫一個程序來從服務器上下載文件。文件服務器由三個文件夾組成,因此我正在嘗試編寫一個自動遍歷目錄並將其複製到我的計算機的腳本。如何使用Java下載在線文件目錄(localhost)

我知道有一個wget的函數可以完成這個遞歸的操作。有沒有辦法在Java中做到這一點? 請你能告訴我應該如何去做或繼續。

謝謝

回答

0

下面是要經過一個在線目錄並返回所有下載所需的鏈接代碼。

之後,我只需要下載每個單獨的鏈接。

import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 

import org.jsoup.Jsoup; 
import org.jsoup.nodes.Document; 
import org.jsoup.nodes.Element; 
import org.jsoup.select.Elements; 

public class WebCrawler { 
    //Created a global list variable to save the links 
    static List<String> createList = new ArrayList<String>(); 

    public static void main(String[] args) throws IOException { 

     String url = "http://localhost:8888"; 
     System.out.println(myCrawler(url)+"\n"+"Size: "+myCrawler(url).size()); 

    }  

    public static List<String> myCrawler(String url) throws IOException{ 
     //Creates an open connection to a link 
     Document doc = Jsoup.connect(url).ignoreContentType(true).get(); 
     Elements links = doc.select("a[href]"); 

     //Recursively iterates through all the links provided on the initial url 
     for (Element i : links) { 
      String link = print("%s", i.attr("abs:href")); 
      if (link.endsWith("/")){myCrawler(link);} //Recursive part, calls back on itself 
      else {createList.add(link);} 
     } 
     return createList; 
    } 

    //Translates the link into a readable string object 
    private static String print(String msg, Object... args){return String.format(msg, args);} 
} 
相關問題