-2

I referred to this link and the code works fine . But what if the size of the file is more than 1 GB ? Can we write directly to output file on the disk instead of create an intermediate ByteArrayOutputStream ?

How to download a file and get the path location locally

Community
  • 1
  • 1
Little bird
  • 1,106
  • 7
  • 28
  • 58
  • It works for 999 MB but does not work for 1 GB, is that correct? – Thomas Weller Oct 20 '15 at 13:18
  • Have you tried with a file more than 1 GB in size ? It should not matter. And: didn't ravindra already answer your question ? – Marged Oct 20 '15 at 13:21
  • We can't. But we can save each portion of data to disk, so we store only some (small) portion of data in memory. – agad Oct 20 '15 at 13:27
  • Pleases don't create followup questions like this. If you are unsatisfied with the answers to the original question, comment on them. Or post a bonus. – Stephen C Oct 20 '15 at 13:28
  • @StephenC : I already commented for this ..Can you please answer my question ? Is this code works for more than 1 GB file size? – Little bird Oct 20 '15 at 13:38
  • No it doesn't work for large files, as I commented on the Answer. (Or at least, it didn't last time I looked.) However, I don't feel inclined to do your programming for you. StackOverflow is a place to help >>programmers<< ... not people who just want to copy-and-paste other peoples' code. – Stephen C Oct 20 '15 at 13:43

1 Answers1

1

Yes, you can.

Instead of creating an intermediate ByteArrayOutputStream you can write the content of the file directly to disk (and you should!).

You can use the InputStream returned by URL and a FileOutputStream, or if you can use Java 8, you should use Files.copy().

On the other hand, if you can't use Java 8, you can also use IOUtils from apache commons-io. It has a very simple method:

public static long copyLarge(InputStream input, OutputStream output)

here's a Java 8 example:

public void testDonwloadUsingJava8() throws Exception {

    URL image = new URL("http://learning.es/blog/wp-content/uploads/2014/08/java.jpg");

    Path tempFile = Files.createTempFile("test-java8-", ".jpg");
    Files.copy(image.openStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);

    System.out.println(tempFile.toString());
    System.out.println(tempFile.toFile().length());
}

Here's an example if you have to use an old version of java:

public void testDownloadFile() throws Exception{

    URL image = new URL("http://learning.es/blog/wp-content/uploads/2014/08/java.jpg");

    File tempFile = File.createTempFile("test-", ".jpg");
    OutputStream output = new FileOutputStream(tempFile);

    try{

        IOUtils.copyLarge(image.openStream(), output);
    } finally {
        output.close();
    }

    System.out.println(tempFile.getPath());
    System.out.println(tempFile.length());
}
jfcorugedo
  • 9,793
  • 8
  • 39
  • 47