I have been trying to download a pdf file from the following URL: http://pdfobject.com/markup/examples/full-browser-window.html
Josh M suggested the following solution that works on his computer. However, I cannot get it to work. I mean the following code saves the file to the destination, however, the downloaded file's weight is only 984 bytes (normally should be 18 Kb). So the file is corrupted. I cannot think of any reason of why this could happen?
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
public final class FileDownloader {
private FileDownloader(){}
public static void main(String args[]) throws IOException{
download("http://pdfobject.com/markup/examples/full-browser-window.html", new File("C:\\Users\\Owner\\Desktop\\temporary\\myFile.pdf"));
download2("http://pdfobject.com/markup/examples/full-browser-window.html", new File("C:\\Users\\Owner\\Desktop\\temporary\\myFile2.pdf"));
}
public static void download(final String url, final File destination) throws IOException {
final URLConnection connection = new URL(url).openConnection();
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
connection.addRequestProperty("User-Agent", "Mozilla/5.0");
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final byte[] buffer = new byte[2048];
int read;
final InputStream input = connection.getInputStream();
while((read = input.read(buffer)) > -1)
baos.write(buffer, 0, read);
baos.flush();
Files.write(destination.toPath(), baos.toByteArray(), StandardOpenOption.WRITE);
input.close();
}
public static void download2(final String url, final File destination) throws IOException {
final URLConnection connection = new URL(url).openConnection();
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
connection.addRequestProperty("User-Agent", "Mozilla/5.0");
final FileOutputStream output = new FileOutputStream(destination, false);
final byte[] buffer = new byte[2048];
int read;
final InputStream input = connection.getInputStream();
while((read = input.read(buffer)) > -1)
output.write(buffer, 0, read);
output.flush();
output.close();
input.close();
}
}