java - 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]
我需要获取这些文件的名称以与数据库中保存的相同文件名进行比较。但是,从文件系统获取的文件名被错误地解码,因此它永远不会等于已经保存在数据库中的文件名。
有谁知道为什么会发生这个问题。有任何想法吗?谢谢!
解决方案
推荐阅读
- php - WooCommerce 的 Mailchimp:删除同步问题的订阅者标签
- amazon-s3 - AWS Glue 和 S3 访问点
- node.js - 如何在 CodeIgniter 4 中集成节点包?
- bash - Bash脚本完成后没有退出,为什么?
- angularjs - 健全性检查:是否可以在 HLS(m3u8)视频流和 angularjs 应用程序(ui)之间进行代理?
- python - 用列表理解解决方案替换 numpy isin
- flutter - Flutter 设置状态未使用新数据更新我的 UI
- python - 瑞典语字符解码错误:这是 API 的错还是我的错?
- python - 无法创建 urls.yaml 以使用 urlwatch
- php - Laravel 导出 Excel - 从不同的表中获取标题