Java - 如何确定文件名是否有效? [英] Java - How to find out whether a File name is valid?

查看:112
本文介绍了Java - 如何确定文件名是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Java应用程序中,我将文件重命名为String参数中提供的文件名。有一种方法

In my Java application I am renaming files to a file name provided in a String parameter. There is a method

boolean OKtoRename(String oldName, String newName)

基本上检查newName是否已被其他文件占用,因为我不想埋葬现有文件。

which basically checks whether the newName isn't already taken by some other file, as I wouldn't want to bury existing ones.

现在我想到,newName String可能不会表示有效的文件名。所以我想把这个检查添加到方法中:

It now occurred to me that perhaps the newName String will not denote a valid file name. So I thought to add this check to the method:

if (new File(newName).isFile()) { 
    return false; 
}

这显然不是正确的方法,因为在大多数情况下newFile尚不存在,因此虽然它 OKtoRename,但该函数返回false。

Which obviously isn't the right way to do it, since in most cases the newFile does not yet exist and therefore although it is OKtoRename, the function returns false.

我想知道,有没有方法(我知道有没有java.io.File对象)像 canExist()?或者我是否必须使用正则表达式以确保newFile字符串不包含无效字符(例如?,*,,:)?我想知道是否在JDK中某处隐藏了一个函数,它会告诉我是否有字符串可能表示有效的文件名。

I was wondering, is there a method (I know there isn't for the java.io.File objects) like canExist()? Or would I have to resort to regex to make sure the newFile String does not contain invalid characters (e.g. ?, *, ", :)? I wonder if there is perhaps a function hidden somewhere in the JDK that would tell me if a string could possibly denote a valid file name.

推荐答案

使用 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.

这篇关于Java - 如何确定文件名是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆