Skip to content

Instantly share code, notes, and snippets.

@abhin4v
Created May 4, 2010 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhin4v/389762 to your computer and use it in GitHub Desktop.
Save abhin4v/389762 to your computer and use it in GitHub Desktop.
A writable file type URL
package net.abhinavsarkar.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import sun.net.www.protocol.file.FileURLConnection;
/**
* Creates a File type URL which provides a writable {@link java.net.URLConnection}
* as opposed to the default {@link sun.net.www.protocol.file.FileURLConnection}
* which is read-only.
*
* There are no checks for the {@link java.io.File} provided.
*
* @author Abhinav Sarkar
*
*/
public class WritableFileUrl {
/**
* @param file File to write to.
* @return A File URL which is writable.
* @throws MalformedURLException
*/
public static URL newInstance(final File file) throws MalformedURLException {
URL url = file.toURI().toURL();
return new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile(),
new URLStreamHandler() {
@Override
protected URLConnection openConnection(final URL url)
throws IOException {
return new FileURLConnection(url, new File(url.getFile())) {
@Override
public OutputStream getOutputStream() throws IOException {
return new FileOutputStream(getURL().getFile());
}};
}});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment