Download file using Java

0
498
Download file using Java

Download file from Internet or from any remote URL should not be a difficult task for Java developers. In this tutorial, I will show you how easy it is to download file using Java.

Download file using Java

At the time of this writing, I will be using Java 8 for the code. So if you’re using different Java versions and all below codes don’t work for you, let me know. Thank you.

Using Java IO

Okay, so to download file in Java, we will need to create two streams:

  • One stream is to read file content from remote server.
  • The other stream is to write and save to hard disk.

Since data exchanging in network is in binary, I mean “bytes”, so we will need to use BufferedInputStream to read file content from Internet. And the other is to use FileOutputStream for writing bytes into local computer.

Take a look at BufferedInputStream, you will notice that input for the constructor must be an instance of InputStream. Where can we get this?

The answer is, we will need to create an instance of URL class, and then use openStream() method to create an InputStream.

BufferedInputStream in = new BufferedInputStream(new URL(REMOTE_FILE_URL).openStream());

Next step is to create an instance of output stream to save file content to disk. Here it is.

FileOutputStream fileStream = new FileOutputStream(SAVING_FILE_NAME);

After having two ready streams, we will need to read each bytes from input stream and write those bytes into output stream. It continues to do that until the end of stream is reach, that is, when number of bytes being read from input stream returning -1.

So the code looks like following:

byte buffer[] = new byte[1024];
int bRead;

while((bRead = in.read(buffer, 0, 1024)) != -1) {
    fileStream.write(buffer, 0, bRead);
}

To finish the job, we have to close both input and output streams to release memory.

fileStream.close();
in.close()

Here the final code that makes use of Java IO to download files from Internet.

public class DownloadFile {
    public static void main(String... args) {
        final String FILE_URL = "https://kodemate.com/wp-content/uploads/2018/08/kodemate.com-logo-design-header-retina-300x99.png";

        BufferedInputStream in;
        FileOutputStream fileStream;

        try {
            in = new BufferedInputStream(new URL(FILE_URL).openStream());
            fileStream = new FileOutputStream("./logo.png");
            byte buffer[] = new byte[1024];
            int bRead;

            while((bRead = in.read(buffer, 0, 1024)) != -1) {
                fileStream.write(buffer, 0, bRead);
            }

            fileStream.close();
            in.close();

        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Above demo code is an example of how to download KodeMate header logo using Java IO.

Be aware that you will be prompted by IDE, such as IntelliJ IDEA, NetBeans, Eclipse… to handle exceptions for the code. In this case, we only need to handle one exception, IOException.

Using Files.copy()

There is another way that seems shorter than previous method.

From Java 7, Files class is available, and it has copy() method, which allows to copy contents from a remote Internet file to local path. It sounds very interesting!

Well, this is the code to demonstrate.

public static void usingFilesCopy() {
    InputStream in = null;
    try {
        in = new URL(FILE_URL).openStream();
        Files.copy(in, Paths.get("./logo.png"), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The first parameter to put in Files.copy() method is an instance of InputStream, which we can retrieve from an instance of URL class.

The next two parameters are self-explained, you can see.

Using Java NIO

Another trick to download file using Java is to make use of Java NIO.

From Java 7, the nio package has been released to allow handling non-blocking operations for network tasks. It offers the channel capability, which is to allow sending data directly between streams without using any buffer.

Instead of dealing with reading data into buffers, and write buffers into output stream, we will need to create two channels to exchange data.

However, to create channel, we still need to pass a stream for it to know where to read from or write to.

Similar to Java IO, we will create two channels: one for read, one for write.

This is the code to download file using Java NIO.

public static void usingJavaNIO() {
    try {
        ReadableByteChannel readChannel = Channels.newChannel(new URL(FILE_URL).openStream());
        FileOutputStream fileStream = new FileOutputStream("./logo.png");
        FileChannel writeChannel = fileStream.getChannel();
        writeChannel.transferFrom(readChannel, 0, Long.MAX_VALUE);
        fileStream.close();
        readChannel.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Summary

As you see, download file using Java is a very easy task to deal with. If you’re a beginner to Java coding, you might see this a bit overwhelming, but take it easy, you will get familiar with it soon.

All code illustrated in this tutorial is posted on Gist, check it out: https://gist.github.com/petehouston/193b60b6b86194cdb53a83be12df6426