1

i try to download a pdf file from url using the code below. It works fine when the file size is under 8k and if the file is up to 8k, it downloads the pdf file but the file is not readable.

Code

 InputStream in = new BufferedInputStream(url.openStream());
                 ByteArrayOutputStream out = new ByteArrayOutputStream();
                 byte[] buf = new byte[1024];
                 int n = 0;
                 while (-1!=(n=in.read(buf)))
                 {
                    out.write(buf, 0, n);
                 }
                 out.close();
                 in.close();
                 byte[] response = out.toByteArray();

                 FileOutputStream fos = new FileOutputStream(new File("C:\\temp\\TEST.pdf"));
                 fos.write(response);
                 fos.close();
                 System.out.println("Download Finished");
samco cosma
  • 39
  • 1
  • 3
  • 11
  • possible duplicate of [how to download large files without memory issues in java](http://stackoverflow.com/questions/7106775/how-to-download-large-files-without-memory-issues-in-java) – StackFlowed Sep 23 '14 at 18:25
  • -1!=(n=in.read(buf) looks odd to me cuz it is c style I guess?. why not (n=in.read(buf)!= -1 – Kick Buttowski Sep 23 '14 at 18:25
  • 2
    I've used your code to download http://www.pdf995.com/samples/pdf.pdf (424 K) and it worked well. If your URL requires some sort of redirection, you'll end up downloading an html page instead of your pdf. So inspect your saved file and check if it's not an HTML file instead. – Leo Sep 23 '14 at 18:31
  • You were right Leo, i tried the same code from home last night when all activities were low at my company and my code downloaded the pdf file in the right format. And when i tried with one of the previous url it was an html file. So the explaination could be the network activities? or what? How could it be redirected? Thank you – samco cosma Sep 24 '14 at 12:39

1 Answers1

0

You may try using the IOUtils.copy(InputStream input, OutputStream output) You can minimize the lines of code. Apache IOUtils

Benoy Prakash
  • 436
  • 5
  • 17
  • 2
    it's easier this way, but why it will fix his/her problem? – Leo Sep 23 '14 at 18:29
  • Or, use [Files.copy](http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#copy-java.io.InputStream-java.nio.file.Path-java.nio.file.CopyOption...-) and avoid the dependency on a third-party library. – VGR Sep 23 '14 at 19:07
  • i forgot to explain how i get the url, it s during a selenium test where i click on a link to download the file. So here the missing code: driver.findElement(By.linkText(DownloadPDFlink)).click(); then i try to get the url with System.out.println("HREF ="+driver.findElement(By.linkText(DownloadPDF)).getAttribute("href")); and after i use thr url object to download the file. – samco cosma Sep 23 '14 at 19:21