0

注意:无效的问题,问题是由!父函数中的放错位置引起的。该问题已被标记,因此可以由版主删除。


我创建了一个函数来检查(文件/目录)路径是否有效,而不检查它是否存在;

public static boolean isValidPath(String path) {
    File f = new File(path);
    try {
        f.getCanonicalPath();
        return true;
    } catch (IOException e) {
        return false;
    }
}

问题是File.getCanonicalPath();当任何目录以点开头时返回错误,尽管它是 Windows 的有效目录路径。这会导致函数返回false应该是true. 例如路径C:\Users\Tim\AppData\Roaming\.minecraft\bin返回false,而C:\Users\Tim\AppData\Roaming\minecraft\bin没有我的世界目录上的点返回true。我的系统上确实存在目录名称中带有点的第一个路径,并且我正在运行 Windows 7 64 位。是否有任何其他功能可以检查路径是否有效,或者我还能做些什么来解决这个问题?

4

2 回答 2

1
import java.io.*;

class TestDirWithDot {

    public static boolean isValidPath(String path) {
        File f = new File(path);
        try {
            f.getCanonicalPath();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void main(String[] arg) {
        System.out.println(System.getProperty("os.name"));
        String path = ".dir";
        System.out.println(isValidPath(path));
    }
}

Windows Vista
true
于 2013-04-21T14:15:32.290 回答
0

我的系统上确实存在目录名称中带有点的第一个路径,并且我正在运行 Windows 7 64 位。

所以你会得到

IOException- 如果发生 I/O 错误,这是可能的,因为规范路径名的构造可能需要文件系统查询。

是否有任何其他功能可以检查路径是否有效?尝试这个:

File file = new File("c:\fileName");
if (!file.isDirectory())
   file = file.getParentFile();
if (file.exists()){
    ...
}
于 2013-04-21T14:16:49.220 回答