You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows控制台传递含西里尔文/多空格路径给Jar时文件检测失败

问题:Windows控制台运行Java Jar时无法正确识别含西里尔文/多空格的文件路径

问题现象

  • IDE中运行Java项目,可正常检测到路径c:\testvideos\[video] ролик\video.mp4,输出EXISTS c:\testvideos\[video] ролик\video.mp4
  • Windows控制台运行Jar包时,输出NOT exists c:\testvideos\[video] ?????\video.mp4,文件检测失败;含连续多个空格的路径也存在同样问题

已尝试方案

  • 设置控制台编码为chcp 65001
  • 启动Jar时添加参数-Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8
  • 应用内尝试多种编码转换(UTF-8与windows-1251互转、UTF-8转ISO-8859-1),但所有转换后的路径检测均失败,输出仍为NOT exists c:\testvideos\[video] ?????\video.mp4

测试代码

import java.io.File;
import java.nio.charset.StandardCharsets;

public class TestFileArgument {
    public static void main(String[] args) {
        String fileName = args[0];
//        String fileName = "c:\\testvideos\\[video] ролик\\video.mp4";
        try {
            checkFileExists(fileName);
            checkFileExists(new String(fileName.getBytes("UTF-8"), "windows-1251"));
            checkFileExists(new String(fileName.getBytes("windows-1251"), "UTF-8"));
            checkFileExists(new String(fileName.getBytes("UTF-8"), StandardCharsets.ISO_8859_1.displayName()));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void checkFileExists(String fileName) {
        if (new File(fileName).exists()) {
            System.out.println("EXISTS " + fileName);
        } else {
            System.out.println("NOT exists " + fileName);
        }

    }

}

控制台启动命令

c:\Users\Ariloum\.jdks\openjdk-21\bin\java.exe -Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8 -jar c:\testvideos\testFileArguments.jar "c:\testvideos\[video] ролик\video.mp4"

补充信息

通过批处理文件echo路径可正常显示西里尔文,无问号替代。


解决办法

  1. 改用java.nio.file.Path替代java.io.File
    File类在处理非ASCII路径存在历史局限性,Path和Files类对Unicode路径支持更完善,修改代码如下:

    import java.nio.file.Files;
    import java.nio.file.Paths;
    
    public class TestFileArgument {
        public static void main(String[] args) {
            String fileName = args[0];
            try {
                checkFileExists(fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static void checkFileExists(String fileName) {
            if (Files.exists(Paths.get(fileName))) {
                System.out.println("EXISTS " + fileName);
            } else {
                System.out.println("NOT exists " + fileName);
            }
        }
    }
    
  2. 强化控制台编码支持

    • 启动Jar前必须先执行chcp 65001,并将控制台字体设置为支持UTF-8的类型(如Consolas、微软雅黑)
    • 改用Windows Terminal替代传统CMD,它对Unicode的兼容性更优
  3. 取消手动编码转换
    手动编码转换易引发乱码,-Dsun.jnu.encoding=UTF-8已能确保JNU层使用UTF-8编码,直接使用JVM传递的参数即可。

  4. 多空格路径处理
    保持启动命令中路径用双引号包裹(当前已实现),Path类会自动正确解析带连续空格的路径。

内容的提问来源于stack exchange,提问作者Ariloum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 05:52:45