Java 中有没有办法在不尝试创建文件的情况下确定路径是否有效? [英] Is there a way in Java to determine if a path is valid without attempting to create a file?
问题描述
我需要确定用户提供的字符串是否是有效的文件路径(即,createNewFile()
是否会成功或抛出异常)但我不想使文件系统膨胀包含无用文件,仅为验证目的而创建.
I need to determine if a user-supplied string is a valid file path (i.e., if createNewFile()
will succeed or throw an Exception) but I don't want to bloat the file system with useless files, created just for validation purposes.
有没有办法在不尝试创建文件的情况下确定我拥有的字符串是否是有效的文件路径?
Is there a way to determine if the string I have is a valid file path without attempting to create the file?
我知道有效文件路径"的定义因操作系统而异,但我想知道是否有任何快速接受 C:/foo
或 /foo的方法code> 并拒绝
banana
.
I know the definition of "valid file path" varies depending on the OS, but I was wondering if there was any quick way of accepting C:/foo
or /foo
and rejecting banana
.
一种可能的方法是尝试创建文件并在创建成功后最终将其删除,但我希望有一种更优雅的方法来实现相同的结果.
A possible approach may be attempting to create the file and eventually deleting it if the creation succeeded, but I hope there is a more elegant way of achieving the same result.
推荐答案
这也会检查目录是否存在.
This would check for the existance of the directory as well.
File file = new File("c:\cygwin\cygwin.bat");
if (!file.isDirectory())
file = file.getParentFile();
if (file.exists()){
...
}
似乎 file.canWrite() 没有明确指示您是否有权写入目录.
It seems like file.canWrite() does not give you a clear indication if you have permissions to write to the directory.
这篇关于Java 中有没有办法在不尝试创建文件的情况下确定路径是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!