Created
May 4, 2010 18:24
-
-
Save abhin4v/389762 to your computer and use it in GitHub Desktop.
A writable file type URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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