Introduction

In this short blogpost I will show you how you can download a file from remote onto you local filesystem. We will use Java SE only. You can always add more error handling like Apache StringUtils if you like.

In my case I was working with the AWS S3 API and needed to download the file onto the local filesystem, before I could upload it into a S3 bucket.

Example implementation

The following class opens a connection to a provided URL and reads the data with a 4KB buffer. Because of the buffer it is not necessary to know the exact file size of the remote/new file. In our case the file will be stored in a the Java temp directory of the filesystem and the path to the file returned.

package me.kamwo.examples.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class FileDownloader {

    /**
     * Returns a path to the downloaded file
     *
     * @param url
     * @param localFilename
     * @return
     * @throws IOException
     */
    public static String downloadFromUrl(URL url, String localFilename) throws IOException {
        InputStream is = null;
        FileOutputStream fos = null;

        String tempDir = System.getProperty("java.io.tmpdir");
        String outputPath = tempDir + "/" + localFilename;

        try {
        	//connect
            URLConnection urlConn = url.openConnection();

            //get inputstream from connection
            is = urlConn.getInputStream();               
            fos = new FileOutputStream(outputPath);   

            // 4KB buffer
            byte[] buffer = new byte[4096];
            int length;

            // read from source and write into local file
            while ((length = is.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            return outputPath;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }
        }
    }
}

To test the Util you can just run the unit test,

which will try to download a logo from Googles server.

package me.kamwo.examples.util;

import org.junit.Test;

import java.io.File;
import java.net.URL;

import static org.junit.Assert.*;

/**
 * Created by kamwo on 23.04.15.
 */
public class FileDownloaderTest {

    @Test
    public void testDownloadFromUrl() throws Exception {
        String result = FileDownloader.downloadFromUrl(new URL("http://google.de/images/srpr/logo11w.png"), "logo11w.png");
        File file = new File(result);
        Boolean fileExists = file.exists();
        file.delete();
        assertTrue("File does not exist.", fileExists);

    }
}