gpt4 book ai didi

java - 转义参数中的非法字符

转载 作者:行者123 更新时间:2023-12-02 06:56:10 25 4
gpt4 key购买 nike

我从 Java 执行一个外部批处理文件并向其传递一个特殊属性。我发现有几个字符被错误地传递到我的批处理文件中。我找不到 ProcessBuilder 类中提到的任何限制,也找不到转义这些字符的方法。

public static void main(String[] args) throws IOException {
/*
* correct processing: almost everything (even #$*%:'\/~?)
* fatal error: |<>
* trimming: ;=&
*/
ProcessBuilder builder = new ProcessBuilder("cmd", "/c", "batch.bat", "a;b;c;d");
final Process process = builder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("Program terminated!");
}

我的批处理文件只是

echo %1

上面的代码仅打印分号 (a) 之前的第一个字符。

我在 Win7 和 JDK 7 64 位上运行它。

目前,我用稀有字符替换所有这些字符,并且反向替换稍后在我的最终脚本中完成。

知道如何在没有任何“翻译”的情况下正确传递这些字符吗?

最佳答案

Microsoft Support Site指出

When a semicolon (;) or equal sign (=) is used as a command line argument in a batch file, it is treated as a blank space.

cmd/? 表示

The special characters that require quotes are:     <space>     &()[]{}^=;!'+,`~

So just use

batch.bat "a;b;c;d"

那就是

new ProcessBuilder("cmd", "/c", "batch.bat", "\"a;b;c;d\"");
<小时/>

后来我发现输出是

"a;b;c;d"Program terminated!

Where the extra " may not be what you want. Use %~1 to strip it off. That is, change your bat file to:

echo %~1

关于java - 转义参数中的非法字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17319224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com