小结论:对于windows盘符目录,必须在末尾加上路径分隔符,不然会路径解析出现问题.
一个莫名的错误,却又不会引起异常.
环境:win7, Eclipse Kepler, java8/java6
main方法中内容
File c = new File("c:");
System.out.println(c.getAbsolutePath());
File c2 = new File("c:\\");
System.out.println(c2.getAbsolutePath());
File d = new File("d:");
System.out.println(d.getAbsolutePath());
File d2 = new File("d:\\");
System.out.println(d2.getAbsolutePath());
console输出:
c:\
c:\
d:\Workspaces\Eclipse\NovelTool
d:\
原因不明,待查找.
File的构造方法中调用了FS的normalize方法来获取path.
查看Win32FileSystem类, 并将于normalize相关变量及方法拷贝至普通类中, 测试normalize方法返回内容正确.
getAbsolutePath方法调用了FS的resolve方法, 应该是该方法出现问题.
使用getPath返回的是d:, 使用
getAbsolutePath则返回d:\Workspaces\Eclipse\NovelTool.
暂无源码, 无法调试resolve方法, 感觉像是bug.
原因依然不明, 待有空下载源码进行debug.
更多无法解释的测试结果:
在单独文件d:\test\Test.java中
-
import java.io.File;
-
-
public class Test{
-
-
public static void main(String[] args){
-
File c = new File("c:");
-
System.out.println(c.getAbsolutePath());
-
System.out.println(c.getPath());
-
System.out.println("--------------");
-
File c2 = new File("c:\\");
-
System.out.println(c2.getAbsolutePath());
-
System.out.println("--------------");
-
File d = new File("d:");
-
System.out.println(d.getAbsolutePath());
-
System.out.println(d.getPath());
-
System.out.println("--------------");
-
File d2 = new File("d:\\");
-
System.out.println(d2.getAbsolutePath());
-
}
-
-
}
在cmd中执行, 天蓝色为执行结果. 意料之外的事, 执行结果居然跟看起来没有任何关系的一个cd命令有关...
-
C:\\Users\\welly-yang>d:
-
-
D:\\>cd test
-
-
D:\\test>javac Test.java
-
-
D:\\test>java Test
-
c:\\Users\\welly-yang
-
c:
-
--------------
-
c:\\
-
--------------
-
d:\\test
-
d:
-
--------------
-
d:\\
-
-
D:\\test>c:
-
-
C:\\Users\\welly-yang>cd ..
-
-
C:\\Users>d:
-
-
D:\\test>java Test
-
c:\\Users
-
c:
-
--------------
-
c:\\
-
--------------
-
d:\\test
-
d:
-
--------------
-
d:\\
File(String)的构造方法会调用FileSystem的prefixLength, 如果传入的是"c:", 会认为是Directory-relative, 但如果传入的是"c:\abc"却会被认为是Absolute local pathname.
具体分支为下面代码红色部分, 不是很理解为什么会这样处理.
上面代码的其余表征现象, 都是该prefixLength返回2以后所导致. 如果传入"c:", prefixLength返回为3, 则上面代码部分正常, 不清楚是否会对其他代码有影响.
-
public int prefixLength(String path) {
-
char slash = this.slash;
-
int n = path.length();
-
if (n == 0) return 0;
-
char c0 = path.charAt(0);
-
char c1 = (n > 1) ? path.charAt(1) : 0;
-
if (c0 == slash) {
-
if (c1 == slash) return 2; /* Absolute UNC pathname \"\\\\\\\\foo\" */
-
return 1; /* Drive-relative \"\\\\foo\" */
-
}
-
if (isLetter(c0) && (c1 == \':\')) {
-
if ((n > 2) && (path.charAt(2) == slash))
-
return 3; /* Absolute local pathname \"z:\\\\foo\" */
-
return 2; /* Directory-relative \"z:foo\" */
-
}
-
return 0; /* Completely relative */
-
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/30112675/viewspace-1591647/
,如需转载,请注明出处,否则将追究法律责任。