java File.getCanonicalPath() 失败示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4489878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:36:32  来源:igfitidea点击:

File.getCanonicalPath() failure examples

javafile-io

提问by gigadot

Does anyone have an experience or know when the method File.getCanonicalPath()will throw an IOException

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

I have tried to look up from the Internet and the best answer is in File APIwhich says

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

"IOException- If an I/O error occurs, which is possible because the construction of the canonical pathname may require filesystem queries"

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

However, it is not clear to me because I still cannot think of a case which this might fail. Can anyone give me concrete examples which can happen on Linux, Windows and other OS (optional)?

但是,我不清楚,因为我仍然想不出可能会失败的案例。谁能给我在 Linux、Windows 和其他操作系统(可选)上可能发生的具体例子?

I reason I want to know is because I want to handle this exception accordingly. Thus, it will be best if I know all the possible failures that can happen.

我想知道的原因是因为我想相应地处理这个异常。因此,最好知道所有可能发生的故障。

回答by dogbane

Here is a Windows example:

这是一个 Windows 示例:

Try calling getCanonicalFileon a file in your CD-drive, but without a CD loaded. For example:

尝试调用getCanonicalFileCD 驱动器中的文件,但没有加载 CD。例如:

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

you will get:

你会得到:

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)

回答by AndrewNR

The IO Exception also occurs if we try creating a File object with Windows device file keywords (see device files) used as file name.
As if you try renaming the file to those keywords, Windows will not let you to make it (no CON, PRN, COM1 etc. file names allowed), Java also won't be able to convert that file name to the correct path.

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

So, any of next next code will trow the IO Exception:

因此,接下来的任何代码都会抛出 IO 异常:

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

However, next code should work:

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

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

回答by LaGrandMere

Seen here in the Sun Bug Database.

Sun Bug 数据库中看到这里。

For JRE 1.4.2_06, File.getCanonicalPath() wasn't working on Windows for a removable drive when there is no media present in the drive.

对于 JRE 1.4.2_06,当驱动器中没有媒体时,File.getCanonicalPath() 不能在 Windows 上用于可移动驱动器。

It was corrected in Java 1.5, but you can see there can be OS-based problems with this method.

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

I don't know of any problem in the current time, but it can happen, that's exactly what the Javadoc says. Usually it's quickly fixed in the newest Java version.

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

回答by ursa

Here is generic example for all OS:

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

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

Before canonicalizing of the file, its validity is checked with java.io.File#isInvalid:

在规范化文件之前,使用 java.io.File#isInvalid 检查其有效性:

final boolean isInvalid() {
    if (status == null) {
        status = (this.path.indexOf('\u0000') < 0) ? PathStatus.CHECKED
                                                   : PathStatus.INVALID;
    }
    return status == PathStatus.INVALID;
}

And if the file is invalid - you'll get an IO exception:

如果文件无效 - 您将收到 IO 异常:

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

Profit!

利润!

回答by Anver Sadhat

One more scenario, When you try to use Operating System restricted/invalid characters as your file name.

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

For Windows \ / : * ? " < > |these are the invalid characters. Try to rename a file with : you will get a balloon/tip message about the invalid characters.

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

Try the Following Java Code.

尝试以下 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());

If the File name contains
* ?you will get java.io.IOException: Invalid argument
| :you will get java.io.IOException: The filename, directory name, or volume label syntax is incorrect

如果文件名包含
* ?你会得到 java.io.IOException: Invalid argument
| :你会得到 java.io.IOException: The filename, directory name, or volume label syntax is wrong


when you use the getCanonicalPath() method.

If we use any of " < >char in the file name, then getCanonicalPath() method is notfailing but when you try to create the file you will be getting the Invalid argument Exception.


当您使用 getCanonicalPath() 方法时。

如果我们" < >在文件名中使用任何字符,那么 getCanonicalPath() 方法不会失败,但是当您尝试创建文件时,您将收到无效参数异常。

Refer jdk7 api

参考jdk7 api

The precise definition of canonical form is system-dependent. Here I have used windows 7.

规范形式的精确定义取决于系统。这里我用的是windows 7。