0

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

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

再次感谢各位,

我感谢所有帮助。

4

1 回答 1

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;
}
于 2013-09-17T12:13:11.210 回答