File.getCanonicalPath()失败示例

时间:2010-12-20 13:06:20

标签: java file-io

有没有人有经验或知道方法File.getCanonicalPath()何时会抛出IOException

我试图从互联网上查找,最好的答案是在File API中说

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

但是,我不清楚,因为我仍然无法想到这可能会失败的情况。任何人都可以给我具体的例子,可以在Linux,Windows和其他操作系统上发生(可选)吗?

我之所以想知道是因为我想要相应地处理这个异常。因此,如果我知道可能发生的所有可能的失败,那将是最好的。

5 个答案:

答案 0 :(得分:18)

这是一个Windows示例:

尝试在CD驱动器中的文件上调用getCanonicalFile,但不加载CD。例如:

new File("D:\\dummy.txt").getCanonicalFile();

你会得到:

Exception in thread "main" java.io.IOException: The device is not ready
    at java.io.WinNTFileSystem.canonicalize0(Native Method)
    at java.io.Win32FileSystem.canonicalize(Win32FileSystem.java:396)
    at java.io.File.getCanonicalPath(File.java:559)
    at java.io.File.getCanonicalFile(File.java:583)

答案 1 :(得分:6)

如果我们尝试使用Windows设备文件关键字创建一个File对象(请参阅device files)作为文件名,也会发生IO异常。
好像您尝试将文件重命名为这些关键字,Windows将不允许您创建它(不允许使用CON,PRN,COM1等文件名),Java也无法将该文件名转换为正确的路径。

因此,下一个代码中的任何一个都会抛出IO Exception:

File file = new File("COM1").getContextPath();
File file = new File("COM1.txt").getContextPath();
File file = new File("C:/somefolder/COM1.txt").getContextPath();

但是,下一个代码应该可以工作:

File file = new File("COM1_.txt").getContextPath();  //underscore wins :)

答案 2 :(得分:3)

Sun Bug Database

对于JRE 1.4.2_06,当驱动器中没有介质时,File.getCanonicalPath()在Windows上无法用于可移动驱动器。

在Java 1.5中已得到纠正,但您可以看到此方法可能存在基于操作系统的问题。

我不知道当前时间有任何问题,但它可能发生,这正是Javadoc所说的。通常它会在最新的Java版本中快速修复。

答案 3 :(得分:2)

以下是所有操作系统的通用示例:

new File("\u0000").getCanonicalFile();

在规范化文件之前,使用java.io.File#isInvalid:

检查其有效性。
final boolean isInvalid() {
    if (status == null) {
        status = (this.path.indexOf('\u0000') < 0) ? PathStatus.CHECKED
                                                   : PathStatus.INVALID;
    }
    return status == PathStatus.INVALID;
}

如果文件无效 - 您将获得IO异常:

public String getCanonicalPath() throws IOException {
    if (isInvalid()) {
        throw new IOException("Invalid file path");
    }
    return fs.canonicalize(fs.resolve(this));
}

利润!

答案 4 :(得分:1)

还有一种情况,当您尝试使用操作系统限制/无效字符作为文件名时。

对于Windows \ / : * ? " < > |,这些是无效字符。尝试使用以下命令重命名文件:您将收到有关无效字符的气球/提示消息。

尝试以下Java代码。

File file = new File("c:/outputlog-2013-09-20-22:15"); 
//A common scenario when you try to append java.util.Date to create a file like
//File newFile = new File(filename + "_" + new Date());
System.out.println(file.getAbsolutePath());
System.out.println(file.getCanonicalPath());

如果文件名包含
* ?你会得到java.io.IOException:无效的参数
| :您将获得java.io.IOException:文件名,目录名或卷标语法不正确


当您使用getCanonicalPath()方法时。

如果我们使用" < >中的任何一个 文件名中的char,然后getCanonicalPath()方法失败,但是当您尝试创建文件时,您将获得Invalid参数Exception。

参考jdk7 api

规范形式的精确定义取决于系统。在这里,我使用了Windows 7。