java中File类的getPath(),getAbsolutePath(),getCanonicalPath()区别

本文通过几个示例对比了Java中File类的getPath()、getAbsolutePath()与getCanonicalPath()方法的区别,解释了它们如何处理相对路径和特殊符号如'.'和'..'。

getPath()

这个是获取定义时的路径,这个没有什么争议的。

getAbsolutePath()

这个是获取绝对路径也就是其父路径 + “定义时的路径”,不会处理".\\","..\\" 

getCanonicalPath()

获取规范化的绝对路径,会处理".\\","..\\" 等

public class mymain {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
          System.out.print("ooooooooooooo\n");
          
          //for(;;){}
          String path = ".\\LXL.txt";
          File file = new File(path);
          try {
			System.out.println(file.getCanonicalPath());
			System.out.println(file.getPath());
			System.out.println(file.getAbsolutePath());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

输出:

ooooooooooooo
D:\soft4dev\eclipse-workspace\test\LXL.txt
.\LXL.txt
D:\soft4dev\eclipse-workspace\test\.\LXL.txt


如果将 代码修改:

public class mymain {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
          System.out.print("ooooooooooooo\n");
          
          //for(;;){}
          String path = "..\\LXL.txt";
          File file = new File(path);
          try {
			System.out.println(file.getCanonicalPath());
			System.out.println(file.getPath());
			System.out.println(file.getAbsolutePath());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

输出:

ooooooooooooo
D:\soft4dev\eclipse-workspace\LXL.txt
..\LXL.txt
D:\soft4dev\eclipse-workspace\test\..\LXL.txt


如果是:

public class mymain {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
          System.out.print("ooooooooooooo\n");
          
          //for(;;){}
          String path = "D:\\LXL.txt";
          File file = new File(path);
          try {
			System.out.println(file.getCanonicalPath());
			System.out.println(file.getPath());
			System.out.println(file.getAbsolutePath());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
输出:

D:\LXL.txt
D:\LXL.txt
D:\LXL.txt


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值