如何使用Java下载在线文件目录(localhost)

时间:2016-07-01 09:23:40

标签: java download directory localhost fileserver

我在“localhost:8888 / fileserver”有一个静态文件服务器。 我试图用java编写程序从服务器下载文件。文件服务器由三个文件夹组成,因此我正在尝试编写一个自动遍历目录并将其复制到我的计算机的脚本。

我知道有一个用于linux的wget函数可以递归地完成此操作。有没有办法在Java中这样做? 请您告诉我应该怎么做或继续。

谢谢

1 个答案:

答案 0 :(得分: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);}
}
相关问题