且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java - 如何确定文件名是否有效?

更新时间:2022-05-08 07:11:21

使用 createNewFile() ,其中只有当文件尚不存在时才会自动创建文件。

Use createNewFile(), which will atomically create the file only if it doesn't yet exist.

如果创建了文件,则该名称有效且不会破坏现有文件。您可以然后使用 FileChannel.transferXXX 操作打开文件并有效地将数据从一个复制到另一个。

If the file is created, the name is valid and it is not clobbering an existing file. You can then open the files and efficiently copy data from one to the other with FileChannel.transferXXX operations.

重要的事情要记住,一般来说,检查和创建应该是原子的。如果你首先检查操作是否安全,那么作为一个单独的步骤执行操作,条件可能有ch与此同时,使操作变得不安全。

An important thing to keep in mind that, in general, the check and the creation should be atomic. If you first check whether an operation is safe, then perform the operation as a separate step, conditions may have changed in the meantime, making the operation unsafe.

此相关帖子提供了额外的思考:用Java移动/复制操作。

Additional food for thought is available at this related post: "Move/Copy operations in Java."

更新:

由于这个答案,我们引入了NIO.2 API,它增加了与文件系统的更多交互。

Since this answer, the NIO.2 APIs have been introduced, which add more interaction with the file system.

假设您有一个交互式程序,并希望在每次击键后验证该文件是否可能有效。例如,您可能只想在条目有效时启用保存按钮,而不是在按保存后弹出错误对话框。创建并确保删除我上面建议的许多不必要的文件似乎一团糟。

Suppose you have an interactive program, and want to validate after each keystroke whether the file is potentially valid. For example, you might want to enable a "Save" button only when the entry is valid rather than popping up an error dialog after pressing "Save". Creating and ensuring the deletion of a lot of unnecessary files that my suggestion above would require seems like a mess.

使用NIO.2,你无法创建 Path 包含对文件系统不合法的字符的实例。一旦您尝试创建路径,就会引发 InvalidPathException

With NIO.2, you can't create a Path instance containing characters that are illegal for the file system. An InvalidPathException is raised as soon as you try to create the Path.

但是,没有用于验证由有效字符组成的非法名称的API,例如Windows上的PRN。作为一种解决方法,实验表明,在尝试访问属性时,使用非法文件名会引发一个明显的异常(例如,使用 Files.getLastModifiedTime())。

However, there isn't an API to validate illegal names comprised of valid characters, like "PRN" on Windows. As a workaround, experimentation showed that using an illegal file name would raise a distinct exception when trying to access attributes (using Files.getLastModifiedTime(), for example).

如果为确实存在的文件指定合法名称,则不会有异常。

If you specify a legal name for a file that does exist, you get no exception.

如果为不存在的文件指定合法名称,则会引发 NoSuchFileException

If you specify a legal name for a file that does not exist, it raises NoSuchFileException.

如果指定了非法名称,则引发 FileSystemException

If you specify an illegal name, FileSystemException is raised.

然而,这看起来非常危险,在其他操作系统上可能不可靠。

However, this seems very kludgey and might not be reliable on other operating systems.