首页 > 解决方案 > Java 8 意外处理文件名中的 unicode 字符

问题描述

我很沮丧地找到问题标题中解释的问题的解决方案。为了帮助您清楚地了解我的问题,我将在下面介绍一些细节。

我有一些名称中有重音的文件存储在目录中。运行ls -lht,它无法正确显示文件。重音解码不正确。但是如果我按下tab键从终端应用自动完成,文件名可以按预期显示。请参阅下面的片段。

tc_pst03@login-01: 6] ls -lht
total 704K
-rw-r----- 1 tc_pst03 pst_pub 86K Oct  9 00:27 Li??2012_Modelling osteomyelitis_Control Model.cps
-rw-r----- 1 tc_pst03 pst_pub 46K Oct  9 00:27 Li??2012_Modelling osteomyelitis_Control Model.xml
-rw-r----- 1 tc_pst03 pst_pub 11K Oct  9 00:27 Li??2012_Modelling osteomyelitis_Control Model.sedml
tc_pst03@login-01: 6] mv Liò2012_Modelling\ osteomyelitis_Control\ Model.

当使用 Java 片段获取所有这些文件时,我得到的结果Li??2012...不是Liò. 我在我们的社区中寻找共享解决方案,但没有解决方案适用于我的问题。下面是我尝试获取这些文件列表的 Java 片段。

List<File> get(String modelId, int revisionNumber) throws ModelException {
        File modelDirectory = new File(modelCacheDir, modelId)
        File revisionDirectory
        List returnedFiles = new LinkedList<File>()
        try {
            revisionDirectory = new File(modelDirectory, revisionNumber.toString())
            if (!revisionDirectory.exists()) {
                throw new FileNotFoundException()
            } else {
                returnedFiles = Files.list(revisionDirectory.toPath())*.toFile() //revisionDirectory.listFiles().toList()
            }
            if (returnedFiles?.isEmpty()) {
                String message = """The cache directory of this model ${modelId} revision ${revisionNumber} is empty. \
 The model cache builder will be launched again."""
                throwModelException(modelId, message)
            }
        } catch (FileNotFoundException me) {
            String message = """The files associated with this model ${modelId}, \
revision ${revisionNumber} hasn't been cached yet"""
            throwModelException(modelId, message)
        }
        return returnedFiles
    }

JAVA_TOOLS_OPTIONS我怀疑 JVM 确实使用了默认字符集,所以我通过在:中定义它来手动启用 UTF-8 export JAVA_TOOLS_OPTIONS=-Dfile.encoding="UTF-8"

一些结果打印如下:

[
._Li?2012_Modelling osteomyelitis_Control Model.xml4483388255187556135.tmp, 
._Li?2012_Modelling osteomyelitis_Control Model.xml8578169841449575225.tmp,
Li��2012_Modelling osteomyelitis_Control Model.sedml, 
._Li?2012_Modelling osteomyelitis_Control Model.xml1056906750418910165.tmp,
Li��2012_Modelling osteomyelitis_Control Model.xml, 
Li��2012_Modelling osteomyelitis_Control Model.cps]

我需要获取这些文件的名称以与数据库中保存的相同文件名进行比较。但是,从文件系统获取的文件名被错误地解码,因此它永远不会等于已经保存在数据库中的文件名。

有谁知道为什么会发生这个问题。有任何想法吗?谢谢!

标签: javafilegroovyunicodenio

解决方案


推荐阅读