22

I've written a bit of code for downloading an episode of a webcast I do. It gets the URL of the episode and gets the place to save it. However, it only downloads up to 16MB and then automatically cancels. I'm not entirely sure what value to change to increase this. Is it possible, and could someone please point me in the right direction? Thankyou!

The downloading code:

    URL url = new URL(episode.getUrl());
    ReadableByteChannel rbc = Channels.newChannel(url.openStream());
    FileOutputStream fos = new FileOutputStream(episode.getLocalSave());
    fos.getChannel().transferFrom(rbc, 0, 1 << 24);
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Ziddia
  • 367
  • 2
  • 4
  • 9
  • 1
    For further discussion, see back reference to what is likely the orginal code snippet http://stackoverflow.com/a/921400/939250 – Donal Lafferty Jan 21 '13 at 17:01

2 Answers2

47

A quick look at the documentation of transferFrom:

public abstract long transferFrom(ReadableByteChannel channel, long position, long count)

WELL.

The value 1<<24 for the count (from the original question) equals 16M

I guess that's the answer to your question :-)

simpleuser
  • 1,617
  • 25
  • 36
emesx
  • 12,555
  • 10
  • 58
  • 91
  • I feel kind of silly now, thanks! I really never think to look in the docs, my bad. – Ziddia Dec 06 '11 at 18:50
  • I'm not great with math, especially since I'm a little unwell at the moment - could somebody please tell me how to increase this to, for example, 200MB? Or any other amount, really. :) – Ziddia Dec 06 '11 at 18:52
  • 24
    He got it wrong originally because of this incredibly popular StackOverlow answer that's causing everyone trouble: http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java – Ben McCann Jan 12 '13 at 21:04
  • Refer to [this answer](http://stackoverflow.com/a/7156178/1535679) for much simpler way to download a file. – Stanley Apr 12 '13 at 04:13
4

here's another solution :

import java.io.*;
import java.net.*;
public class DownloadFile
{

    public static void main(String args[]) throws IOException
    {

        java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL(episode.getUrl()).openStream());
        java.io.FileOutputStream fos = new java.io.FileOutputStream(episode.getLocalSave());
        java.io.BufferedOutputStream bout = new BufferedOutputStream(fos);
        byte data[] = new byte[1024];
        int read;
        while((read = in.read(data,0,1024))>=0)
        {
            bout.write(data, 0, read);
        }
        bout.close();
        in.close();
    }
}
wolpers
  • 121
  • 1
  • 5
amrfaissal
  • 1,060
  • 1
  • 7
  • 18