java中URL和File的相互转化
来源:互联网 发布:raptor编程1到100之和 编辑:程序博客网 时间:2024/06/04 19:06
来源:http://www.cnblogs.com/youxin/archive/2012/04/22/2464515.html
java中URL和File的相互转化
URL用于网络,所以带有明显的protocol,而且对于中文及符号支持的很不好。File就是我们平常系统中的文件路径了,对于中文及符号都支持,但是已经没有protocol了。所以,虽然两者都可以表示文件路径,但是却不能混用了。
URL to File:
URL url=……;
File file=new File(url.toURI()); 或 file=new File(url.getFile());
File to URL:
File file=……;
URL url=file.toURL();
A file object is used to a give a filename. Creating the File object doesn't mean that a file exists. It may be that the does not exist. Suppose if the file exists, first of all we need to convert the file object in URL, for this we use a method toURL(). It returns aURL object and throws MalformedException. After this we will convert this URL to a file object by using getFile() method. We will read this file by using BufferedReader object.
toURL() : It is used to convert the file name into the URL. getFile() : This is the method of the URL class, is used to get the file name from the URL.
Here is the code of the program:
import java.io.*;import java.net.*;public class ConstructFileNamePath{ public static void main(String[] args){ File file=new File("C:/work/chandan/deepak.txt"); URL url=null; try{ //The file may or may not exist url=file.toURL(); //file:/C:/work/chandan/deepak.txt System.out.println("The url is" + url); // change the URL to a file object file=new File(url.getFile()); // c:/work/chandan/deepak.txt System.out.println("The file name is " + file); int i; //opens an input stream InputStream is=url.openStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); do{ i=br.read(); System.out.println((char)i); }while (i!=-1); is.close(); } catch (MalformedURLException e){ System.out.println("Don't worry,exception has been caught" + e); } catch (IOException e){ System.out.println(e.getMessage()); } }}
The url is file:/C:/work/chandan/deepak.txt
The file name is C:\work\chandan\deepak.txt
C:\work\chandan\deepak.txt (系统找不到指定的路径。)
- java中URL和File的相互转化
- java中URL和File的相互转化
- java中URL和File的相互转化
- java中URL和File的相互转化
- java中URL和File的相互转化
- java中URL和File的相互转化
- java中URL和File的相互转化
- java中URL和File的相互转化 及两者的使用场景
- Java中的URL与FILE相互转化
- java中String和int之间的相互转化
- Java中byte[]、char[]和String的相互转化
- java中String类型和char[]类型的相互转化
- Java中二进制和十进制之间的相互转化
- java中int和Integer的相互转化
- JAVA中IP和整数相互转化
- JAVA中IP和整数相互转化
- JAVA中IP和整数相互转化
- JAVA中IP和整数相互转化
- 有关hibernate相关的延迟加载和缓存机制
- Html中的iframe,frameset frame
- mysql数据库执行“数据传输”出错
- 做到这一点,你也可以成为优秀的程序员
- loadrunner Web_类函数之web_submit_data()
- java中URL和File的相互转化
- 对8086中的段的理解
- 基于XML配置的SSH三大框架整合
- 第四周项目3—单链表应用(2)
- 双向链表在java中的应用举例-LinkedList
- axios模块在vue开发中如何使用引入,如何注册全局方法
- 2017安卓最全框架
- Utgard_OpcClient使用简要指南
- 第4周项目5- 猴子选大王