file.getPath() getAbsolutePath() getCanonicalPath()区别

本文通过实例详细解释了Java中File类的getPath(), getAbsolutePath(), 和getCanonicalPath()方法的区别及应用场景,帮助读者理解如何获取文件的不同路径形式。

package com.java;

import java.io.File;
import java.io.IOException;

public class GetFilePath {
	 public static void main(String[] args) throws IOException
	 {
	  System.out.println("------默认相对路径,取得路径不同-----");
	  File f = new File("..\\src\\file");
	  System.out.println(f.getPath());
	  System.out.println(f.getAbsolutePath());
	  System.out.println(f.getCanonicalPath());
	  System.out.println("------默认相对路径,取得路径不同-----");
	  File f2 = new File(".\\src\\file");
	  System.out.println(f2.getPath());
	  System.out.println(f2.getAbsolutePath());
	  System.out.println(f2.getCanonicalPath()); 
	  System.out.println("------默认绝对路径,取得路径相同-----");
	  File f3 = new File("C:\\src\\file");
	  System.out.println(f3.getPath());
	  System.out.println(f3.getAbsolutePath());
	  System.out.println(f3.getCanonicalPath()); 
	  
	//   执行结果为:
	//	  ------默认相对路径,取得路径不同-----
	//	  ..\src\file
	//	  E:\workspace\test\..\src\file
	//	  E:\workspace\src\file
	//	  ------默认相对路径,取得路径不同-----
	//	  .\src\file
	//	  E:\workspace\test\.\src\file
	//	  E:\workspace\test\src\file
	//	  ------默认绝对路径,取得路径相同-----
	//	  C:\src\file
	//	  C:\src\file
	//	  C:\src\file
	//  
	//   比较可以得到
	//   getPath()返回的是构造方法里的路径,不做任何处理
	//   getAbsolutePath()返回的是 user.dir+getPath(),也就是执行路径加上构造方法中的路径
	//   getCanonicalPath()返回的是将符号完全解析的路径,也就是全路径
	 }
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值