我正在尝试检查用户输入的文件路径对于操作系统是否有效,我认为这可以通过 Paths.get(filePath) 来实现,所以我编写了这个简单的函数
public static boolean isValidFilename(String s)
{
try
{
Paths.get(s);
return true;
}
catch (InvalidPathException e)
{
return false;
}
}
但在 Windows 8 上,它将成功返回 false
c:\File::
不会的
c:\File..
这是一个错误,还是我的误解
最佳答案
这是你的误会。冒号在 Windows 中不是合法的文件名字符,而是句点“.”是。
第二个文件有效......它与C:/File..
相同。 (即 C://File..
和 C:/File..
是同一位置)
编辑:请在此处查看此问题:How to create a filename with a trailing period in Windows?
我已经在我的系统中尝试过了,不幸的是我的结果好坏参半......但是上面的答案仍然很好读......
Edit2:我已经运行了以下代码,它现在对我有用:
File file = new File("\\\\?\\C:/Temp/File..");
FileOutputStream fos = new FileOutputStream(file);
fos.write("Foo".getBytes());
fos.close();
看来 \\?\
构造在 java.io.File
中有效,但在 java.nio.file.Path
中无效>
如果您打印出异常,您还会更多地了解问题所在......
java.nio.file.InvalidPathException: Illegal char <:> at index 7: C:/File::
at sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:194)
at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:165)
at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:89)
at sun.nio.fs.WindowsPath.parse(WindowsPath.java:106)
at sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:267)
at java.nio.file.Paths.get(Paths.java:95)
关于java - 为什么这个java函数不指示文件路径无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19815224/