Scaricare un file da internet in Java
Vi propongo due metodi per scaricare un file da internet in Java.
Il primo caso è usando le Java NIO, e quindi non servono librerie esterne:
public class Main {
public static void main(String[] args) {
String remoteFile = "ftp://ftp.arin.net/pub/stats/arin/delegated-arin-extended-latest";
String localFile = "/home/matte/Desktop/file.txt";
try {
URL website = new URL(remoteFile);
try (
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(localFile)) {
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}