java中URL和File的相互转化

18 篇文章 0 订阅

 来源: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 (系统找不到指定的路径。)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值