简体   繁体   中英

Downloading a file from sourceforge [i.e No specific file name]

I want to make an installer for my project. I know how to do this, but only when I have the specific name of the file on the web page that I wish to download. Sourceforge can automatically find the latest download, but how can I get this file through use of Java? Thanks.

If you need it, project downloads link is here [Not the automatic download]: https://sourceforge.net/projects/herobrawl/files/?source=navbar

Thanks again guys,

I appreciate all help.

I'm gonna show you how to do it with HTML parsing. But if the SourceForge API supports this feature, it would be better to do it with the SourceForge API.

To run this code you will need 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM