java不区分大小写文件。在区分大小写的文件系统上等于
我有一个字符串形式的文件路径。在Java中,我需要确定文件系统中是否存在该文件(我们的代码需要跨平台,因为它在Windows、Linux和OS X上运行)
问题是,文件路径和文件本身的大小写可能不匹配,即使它们确实代表同一个文件(可能这是因为它们起源于Windows,并且没有注意到差异)
例如,我有一个文件路径“ABC.txt”。文件系统中存在一个名为“abc.txt”的文件。以下代码将在Windows上返回true,但在Linux上返回false:
new File("ABC.txt").exists();
确定文件是否存在的最佳方法是什么,以及是否存在该文件以在文件系统上返回该文件的句柄
# 1 楼答案
正如jwaddell所说,看起来非常慢的递归路径检查(显然)是实现这一点的唯一方法。下面是我用java编写的函数,它接受一个字符串,即文件路径。如果文件路径的字符串表示形式存在,并且与windows报告的大小写敏感度相同,则返回true,否则返回false
# 2 楼答案
这是我的Java 7解决方案,适用于父路径已知且相对子路径可能与磁盘上的路径不同的情况
例如,给定文件
/tmp/foo/biscuits
,该方法将使用以下输入向文件正确返回Path
:/tmp
和foo/biscuits
/tmp
和foo/BISCUITS
/tmp
和FOO/BISCUITS
/tmp
和FOO/biscuits
请注意,此解决方案尚未经过可靠的测试,因此应将其视为一个起点,而不是一个可用于生产的片段
# 3 楼答案
此方法将告诉您是否存在具有确切名称的文件(路径部分不区分大小写)
# 4 楼答案
从目录(^{} )中获取文件列表,并使用
equalsIgnoreCase()
比较名称# 5 楼答案
至于问题的第一部分:使用Path.toRealPath。它不仅处理大小写敏感,还处理符号链接(取决于作为参数提供的选项),等等。这需要Java 7或更高版本
至于问题的第二部分:不确定你说的“把手”是什么意思
# 6 楼答案
如果差异是随机的,那么对我来说,Shimi的解决方案包括递归路径段检查是最好的解决方案。乍一看,这听起来很难看,但您可以将魔法隐藏在一个单独的类中,并实现一个简单的API来返回给定文件名的文件句柄,这样您就可以看到类似于
Translator.translate(file)
调用的东西也许,这种差异是静态的、可预测的。那么我更喜欢一本字典,它可以用来将给定的文件名转换为Windows/Linux文件名。与其他方法相比,这种方法有很大的优势:获得错误文件句柄的风险更小
如果字典是静态的,那么可以创建并维护一个属性文件。如果它是静态的,但更复杂,比如一个给定的文件名可以被翻译成多个可能的目标文件名,我会用
Map<String, Set<String>>
数据结构备份这个口述类(Set
优先于List
,因为没有重复的替代项)