Java生成含中文的UTF-16LE编码desktop.ini在Win11中失效问题
问题:Java创建UTF-16 LE编码的desktop.ini中文别名失效
我尝试用Java生成desktop.ini文件,给Windows 11文件夹设置类似「我的文档」的自定义别名。以下是测试代码:
@Test public void createDesktopIni() throws IOException { String folderPath = Write a folder path here; String iniPath = folderPath + "\\desktop.ini"; File file = new File(iniPath); // delete and recreate if exist if (file.exists()) { file.delete(); } file.createNewFile(); // Write content String alternativeName = "Alternative Name"; //alternativeName = "这是一个中文别名"; OutputStreamWriter oStreamWriter = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_16LE); oStreamWriter.write("[.ShellClassInfo]\nLocalizedResourceName = " + alternativeName); oStreamWriter.flush(); oStreamWriter.close(); // Set system attribute Files.setAttribute(Paths.get(folderPath), "dos:system", true, LinkOption.NOFOLLOW_LINKS); Files.setAttribute(Paths.get(iniPath), "dos:system", true, LinkOption.NOFOLLOW_LINKS); Files.setAttribute(Paths.get(iniPath), "dos:hidden", true, LinkOption.NOFOLLOW_LINKS); }
问题现象
- 设置英文别名时,
desktop.ini正常工作,VSCode可正常打开 - 设置中文别名(如
"这是一个中文别名")时,文件失效;用VSCode打开会提示编码错误,手动选择「以UTF-16 LE编码重新打开」并保存后,别名恢复正常
已尝试的编码情况
- UTF-8:文件生效,但资源管理器中中文显示乱码
- GBK:中文显示正常且生效,但希望和系统默认(如「我的文档」的
desktop.ini)一致使用UTF-16 LE编码 - UTF-16:直接失效,生成的文件实际为UTF-16 BE编码
解决方案
问题核心:Windows Shell识别UTF-16编码的desktop.ini必须依赖BOM(字节顺序标记),但Java的OutputStreamWriter使用StandardCharsets.UTF_16LE时不会自动写入BOM,导致系统无法正确识别编码。
修改后的代码(手动写入UTF-16 LE的BOM):
@Test public void createDesktopIni() throws IOException { String folderPath = "D:\\TestFolder"; // 替换为目标文件夹路径 String iniPath = folderPath + "\\desktop.ini"; File file = new File(iniPath); // 先删除旧文件再重建 if (file.exists()) { file.delete(); } file.createNewFile(); String alternativeName = "这是一个中文别名"; // 使用try-with-resources自动管理流,避免资源泄漏 try (FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter oStreamWriter = new OutputStreamWriter(fos, StandardCharsets.UTF_16LE)) { // 手动写入UTF-16 LE的BOM:0xFF 0xFE(必须写在编码内容之前) fos.write(0xFF); fos.write(0xFE); // 写入desktop.ini内容 oStreamWriter.write("[.ShellClassInfo]\nLocalizedResourceName = " + alternativeName); } // 设置文件夹和desktop.ini的系统、隐藏属性 Files.setAttribute(Paths.get(folderPath), "dos:system", true, LinkOption.NOFOLLOW_LINKS); Files.setAttribute(Paths.get(iniPath), "dos:system", true, LinkOption.NOFOLLOW_LINKS); Files.setAttribute(Paths.get(iniPath), "dos:hidden", true, LinkOption.NOFOLLOW_LINKS); }
说明
- UTF-16 LE的BOM是
0xFF 0xFE,写入后Windows Shell能正确识别文件编码,中文别名即可正常显示 - 使用
try-with-resources语法替代手动关闭流,更安全且代码更简洁 - 系统属性设置是必须的,否则
desktop.ini不会被Windows Shell读取
内容的提问来源于stack exchange,提问作者Meltryllis
相关产品推荐
相关产品推荐

