Skip to content

Java Examples Repository – First Example: Copy a File from a URL to a Local Path

Last updated on 2012-12-09

There are programming tasks that I don’t do a lot, and they are forgotten in the depths of my brain, never to be seen again. That is why I try to store all of the code I have written so that I can fetch examples when needed (and now that github exists, why not share it with the world?).
So my first example in the new public repository is this: how to copy a file (maybe binary) from a URL to a local path. The code is pretty simple:

/*******************************************************************************
 * Copyright (c) 2012 Arieh 'Vainolo' Bibliowicz
 * You can use this code for educational purposes. For any other uses
 * please contact me: vainolo@gmail.com
 *******************************************************************************/
package com.vainolo.examples.net;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;

public class NetworkFileCopier {
	public static File copyFileFromWeb(String address, String filePath) throws Exception {
		byte[] buffer = new byte[1024];
		int bytesRead;

		URL url = new URL(address);
		BufferedInputStream inputStream = null;
		BufferedOutputStream outputStream = null;
		URLConnection connection = url.openConnection();
		// If you need to use a proxy for your connection, the URL class has another openConnection method.
		// For example, to connect to my local SOCKS proxy I can use:
		// url.openConnection(new Proxy(Proxy.Type.SOCKS, newInetSocketAddress("localhost", 5555)));
		inputStream = new BufferedInputStream(connection.getInputStream());
		File f = new File(filePath);
		outputStream = new BufferedOutputStream(new FileOutputStream(f));
		while ((bytesRead = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, bytesRead);
		}
		inputStream.close();
		outputStream.close();
		return f;
	}
}

The code is available on the Vainosamples repository. Oh, and if you have a better implementation, please do tell me!

Published inProgramming

Be First to Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.