您的位置:首页 > 编程语言 > PHP开发

File的getPath getAbsolutePath和getCanonicalPath的不同

2014-06-17 14:47 666 查看
1.getPath()与getAbsolutePath()的区别

public static void test1(){
File file1 = new File(".\\test1.txt");
File file2 = new File("D:\\workspace\\test\\test1.txt");
System.out.println("-----默认相对路径:取得路径不同------");
System.out.println(file1.getPath());
System.out.println(file1.getAbsolutePath());
System.out.println("-----默认绝对路径:取得路径相同------");
System.out.println(file2.getPath());
System.out.println(file2.getAbsolutePath());

}


得到的结果:

-----默认相对路径:取得路径不同------
.\test1.txt
D:\workspace\test\.\test1.txt
-----默认绝对路径:取得路径相同------
D:\workspace\test\test1.txt
D:\workspace\test\test1.txt


2.getAbsolutePath()和getCanonicalPath()的不同

public static void test2() throws Exception{
File file = new File("..\\src\\test1.txt");
System.out.println(file.getAbsolutePath());
System.out.println(file.getCanonicalPath());
}


得到的结果:


D:\workspace\test\..\src\test1.txt


D:\workspace\src\test1.txt
可以看到CanonicalPath不但是全路径,而且把..或者.这样的符号解析出来。

3.getCanonicalPath()和自己的不同。

单下边这段代码是看不到结果的,要配合一定的操作来看。下边操作步骤,同时讲解

public static void test3() throws Exception{
File file = new File("D:\\Text.txt");
System.out.println(file.getCanonicalPath());
}


步骤:
确定你的系统是Windows系统。
(1),确定D盘下没有Text.txt这个文件,直接执行这段代码,得到的结果是:


D:\Text.txt
注意这里试大写的Text.txt
(2)在D盘下建立一个文件,名叫text.txt,再次执行代码,得到结果


D:\text.txt

同样的代码得到不同的结果。
同时可以对比getAbsolutePath()看看,这个得到的结果是一样的。

原因:
window
是大小写不敏感的,也就是说在windows上test.txt和Test.txt是一个文件,所以在windows上当文件不存在时,得到的路径就是按
照输入的路径。但当文件存在时,就会按照实际的情况来显示。这也就是建立文件后和删除文件后会有不同的原因。文件夹和文件类似。

三、最后:
1,尝试在linux下执行上边的步骤,两次打印的结果是相同的,因为linux是大小写敏感的系统。
2,手动删掉test.txt,然后尝试执行下边代码

public static void test4() throws Exception{
File file = new File("D:\\Text.txt");
System.out.println(file.getCanonicalPath());
File file1 = new File("D:\\text.txt");
file1.createNewFile();
file = new File("D:\\Text.txt");
System.out.println(file.getCanonicalPath());
}


public static void test3() throws Exception{
File file1 = new File("D:\\text.txt");
file1.createNewFile();
File file = new File("D:\\Text.txt");
System.out.println(file.getCanonicalPath());
}


执行上边两个函数,看看结果,然后思考一下为什么?
1,的结果是两个大写,
2,的结果试两个小写
连续两个大写的,是否跟上边的矛盾 ?
这是因为虚拟机的缓存机制造成的。第一次File file = new File("D:\\Text.txt");决定了结果.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: