Reputation: 33
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.
Upvotes: 0
Views: 427
Reputation: 22243
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;
}
Upvotes: 1