奇怪的getName()导致
问题描述:
我有一些代码,从UNC路径读取名称:奇怪的getName()导致
File f = new File(//fileshare/folder/file.txt)
System.out.println(f.getName())
在Windows上给出了:
file.txt
,但在Linux上得到:
//fileshare/folder/file.txt
为什么?
答
在我的系统(Ubuntu的12.04),它给file.txt
:
$ cat Test.java
import java.io.File;
class Test {
public static void main(String[] args) {
File f = new File("//fileshare/folder/file.txt");
System.out.println(f.getName());
}
}
$ javac Test.java && java Test
file.txt
f.getPath()
回报/fileshare/folder/file.txt
,这表明多斜线就减少了一个,因为(需要?)在Unix系统上是习惯。
当然,UNC路径在除Windows以外的任何地方都没有意义。
答
尝试使用来自Apache Commons的org.apache.commons.io.FilenameUtils,getName()方法应确保对完整路径进行一致的解析,无论您正在运行的平台如何。
你可以在两个系统上打印'File.separatorChar',看看会发生什么? – dasblinkenlight