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

Windows7升级至10后测试出现MalformedURLException问题求助

解决Windows 10升级后触发MalformedURLException的问题

你遇到的问题核心是Windows系统升级后,资源URL的路径处理逻辑出现了兼容性问题——Windows 10下的路径(比如项目目录、用户文件夹)更容易包含空格或特殊字符,而URL.getFile()返回的是未解码的路径字符串(空格会被转成%20),直接传给RunScript.execute会被当作无效路径,触发URL格式异常。

推荐解决方案:用输入流替代文件路径

RunScript.execute有重载方法支持直接传入输入流,完全绕开路径解码的坑,代码更可靠:

@BeforeClass
public static void createSchema() throws Exception {
    log.info("Creating H2 CA_MANAGER schema");
    URL schemaDDL = Thread.currentThread().getContextClassLoader().getResource("create_cam_test.sql");
    // 直接获取资源输入流,无需处理路径字符串
    try (InputStream is = schemaDDL.openStream()) {
        RunScript.execute(TestConfig.URL, TestConfig.USER, TestConfig.PASSWORD, is, null, false);
    }
    log.info("Running H2 CA_MANAGER DDL");
    // 后续DDL脚本也用同样方式处理
    URL ddl = Thread.currentThread().getContextClassLoader().getResource("your_other_script.sql");
    try (InputStream ddlIs = ddl.openStream()) {
        RunScript.execute(TestConfig.URL, TestConfig.USER, TestConfig.PASSWORD, ddlIs, null, false);
    }
}

备选方案:手动解码URL路径

如果一定要用文件路径的方式,需要对getFile()返回的字符串做URL解码,把转义字符还原成系统能识别的格式:

@BeforeClass
public static void createSchema() throws Exception {
    log.info("Creating H2 CA_MANAGER schema");
    URL schemaDDL = Thread.currentThread().getContextClassLoader().getResource("create_cam_test.sql");
    // 用UTF-8解码URL路径,还原空格等特殊字符
    String decodedPath = URLDecoder.decode(schemaDDL.getFile(), StandardCharsets.UTF_8.name());
    RunScript.execute(TestConfig.URL, TestConfig.USER, TestConfig.PASSWORD, decodedPath, null, false);
    log.info("Running H2 CA_MANAGER DDL");
    // 后续DDL脚本同理处理
    URL ddl = Thread.currentThread().getContextClassLoader().getResource("your_other_script.sql");
    String ddlDecodedPath = URLDecoder.decode(ddl.getFile(), StandardCharsets.UTF_8.name());
    RunScript.execute(TestConfig.URL, TestConfig.USER, TestConfig.PASSWORD, ddlDecodedPath, null, false);
}

为什么Windows 10才出问题?

Windows 7时代很多用户习惯把项目放在无空格的路径(比如D:\dev\project),而Windows 10默认的用户目录、Program Files目录都包含空格,当你的项目或资源文件路径涉及这些目录时,URL.getFile()返回的转义字符串就会让RunScript无法识别正确路径,最终抛出异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:48:36