[Arakhnę-Dev] [56] Add FileSystem.UrlToFile() function.

[ Thread Index | Date Index | More arakhne.org/dev Archives ]


Revision: 56
Author:   galland
Date:     2009-04-18 20:46:16 +0200 (Sat, 18 Apr 2009)

Log Message:
-----------
Add FileSystem.UrlToFile() function.

Modified Paths:
--------------
    trunk/arakhneVmutils/java/src/main/java/org/arakhne/vmutil/FileSystem.java


Modified: trunk/arakhneVmutils/java/src/main/java/org/arakhne/vmutil/FileSystem.java
===================================================================
--- trunk/arakhneVmutils/java/src/main/java/org/arakhne/vmutil/FileSystem.java	2009-04-16 20:45:37 UTC (rev 55)
+++ trunk/arakhneVmutils/java/src/main/java/org/arakhne/vmutil/FileSystem.java	2009-04-18 18:46:16 UTC (rev 56)
@@ -26,6 +26,10 @@
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
 import java.nio.channels.FileChannel;
 
 
@@ -387,5 +391,42 @@
 		return null;
 	}
 
+	/** Convert an URL which represents a local file into a File.
+	 * 
+	 * @param url is the URL to convert.
+	 * @return the file.
+	 * @throws IllegalArgumentException is the URL was malformed.
+	 */
+	public static File UrlToFile(URL url) {
+		URI uri;
+		try {
+			// this is the step that can fail, and so
+			// it should be this step that should be fixed
+			uri = url.toURI();
+		}
+		catch (URISyntaxException e) {
+			// OK if we are here, then obviously the URL did
+			// not comply with RFC 2396. This can only
+			// happen if we have illegal unescaped characters.
+			// If we have one unescaped character, then
+			// the only automated fix we can apply, is to assume
+			// all characters are unescaped.
+			// If we want to construct a URI from unescaped
+			// characters, then we have to use the component
+			// constructors:
+			try {
+				uri = new URI(url.getProtocol(), url.getUserInfo(), url
+						.getHost(), url.getPort(), url.getPath(), url
+						.getQuery(), url.getRef());
+			}
+			catch (URISyntaxException e1) {
+				// The URL is broken beyond automatic repair
+				throw new IllegalArgumentException("broken URL: " + url); //$NON-NLS-1$
+			}
+
+		}
+		return new File(uri);
+	}
+	
 }
 


Mail converted by MHonArc 2.6.19+ http://listengine.tuxfamily.org/