在这篇文章中,将演示如何将java.io.File
转换为java.net.URL
,反之亦然。
以下示例演示了将File转换为URL。文件:FileToUrlExample.java –
package com.yiibai.tutorial.io; import java.io.File; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; /** * @author yiibai */ public class FileToUrlExample { public static void main(String[] args) { File file = new File("C:/Program Files/Java/jdk1.8.0_71/COPYRIGHT"); if (file.exists()) { System.out.println("PATH: " + file.getPath()); // Convert file to URI URI uri = file.toURI(); System.out.println("URI: " + uri.toString()); // Convert URI to URL URL url; try { url = uri.toURL(); System.out.println("URL: " + url.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } } } }
执行上面代码,得到以下结果:
PATH: C:/Program Files/Java/jdk1.8.0_71/COPYRIGHT URI: file:/C:/Program%20Files/Java/jdk1.8.0_71/COPYRIGHT URL: file:/C:/Program%20Files/Java/jdk1.8.0_71/COPYRIGHT
以下示例演示了将URL转换为File。
文件:UrlToFileExample.java –
package com.yiibai.tutorial.io; import java.io.File; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; /** * @author yiibai */ public class UrlToFileExample { public static void main(String[] args) { try { URL url=new URL("file:/C:/Program%20Files/Java/jdk1.8.0_71/COPYRIGHT"); System.out.println("URL: "+url.toString()); //Convert URL to URI URI uri=url.toURI(); System.out.println("URI: "+uri.toString()); //Convert URI to File File file=new File(uri.getPath()); System.out.println("PATH: "+file.getAbsolutePath()); } catch (MalformedURLException | URISyntaxException e) { e.printStackTrace(); } } }
执行上面示例代码,得到以下结果:
URL: file:/C:/Program%20Files/Java/jdk1.8.0_71/COPYRIGHT URI: file:/C:/Program%20Files/Java/jdk1.8.0_71/COPYRIGHT PATH: C:/Program Files/Java/jdk1.8.0_71/COPYRIGHT `
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264098.html