从sourceforge下载文件[即没有特定的文件名]

时间:2013-09-17 10:11:54

标签: java sourceforge

我想为我的项目制作一个安装程序。我知道如何做到这一点,但只有当我在网页上有我想下载的文件的特定名称时。 Sourceforge可以自动找到最新的下载,但是如何通过使用Java获取此文件?感谢。

如果您需要,项目下载链接在这里[不是自动下载]:https://sourceforge.net/projects/herobrawl/files/?source=navbar

再次感谢你们,

我感谢所有人的帮助。

1 个答案:

答案 0 :(得分:1)

我将告诉你如何使用HTML解析来完成它。 如果SourceForge API支持此功能,最好使用SourceForge API。

要运行此代码,您需要JSOUP

public static void main(String[] args) throws IOException {
    System.out.println("Parsing the download page...");
    //Get the versions page
    Document doc = Jsoup.connect("http://sourceforge.net/projects/herobrawl/files/").get();
    //Every link to the download page has class "name"
    Elements allOddFiles = doc.select(".name");
    //Elements are sorted by date, so the first element is the last added
    Element lastUploadedVersion = allOddFiles.first();
    //Get the link href
    String href = lastUploadedVersion.attr("href");
    //Download the jar
    System.out.println("Parsing done.");
    System.out.println("Downloading...");
    String filePath = downloadFile(href, "newVersion.jar");
    System.out.println("Download completed. File saved to \"" + filePath + "\"");
}

/**
 * Downloads a file
 *
 * @param src The file download link
 * @param fileName The file name on the local machine
 * @return The complete file path
 * @throws IOException
 */
private static String downloadFile(String src, String fileName) throws IOException {
    String folder = "C:/myDirectory";//change this to whatever you need
    //Open a URL Stream
    URL url = new URL(src);
    InputStream in = url.openStream();
    OutputStream out = new BufferedOutputStream(new FileOutputStream(folder + fileName));
    for (int b; (b = in.read()) != -1;) {
        out.write(b);
    }
    out.close();
    in.close();
    return folder + fileName;
}
相关问题