从 java 中为 cmd 文件转义“< >”

escape "< >" for cmd file from java

在 cmd.exe 我试试这个 :

echo " read "book <init>""

错误是:

系统找不到指定的文件。

适用于

echo "read "book ^<init^>""

但是如果我想从 java 作为参数发送,它将不起作用:

String s4 = "read \"book ^<init^> \"" ;

如何从 java 转义 < > for cmd?

完整代码:

    public static void main(String[] args) throws IOException, InterruptedException{

    List<String> paramsArray = new ArrayList<String>();

    String s = "read \"book ^<init^> \"" ;
    paramsArray.add("exec.cmd"); //cmd file that only has echo %*
    paramsArray.add(s);

    ProcessBuilder process = new ProcessBuilder(paramsArray).inheritIO(); 

    Process p = process.start();

    int exitStatus = p.waitFor();

    System.out.println("exitStatus is " + exitStatus);

    if (exitStatus == 0)
    {
      System.out.println("Ok!");
    }
    else{

        System.out.println("Not ok!");
    }
}

我想你的问题是:


"How can I pass an argument to a bat file that contains multiple quotes and special characters in it , such that the bat file will not interpret it ?"


您可以将 Java 中的双引号 ("") 替换为单引号 :

your_string= your_string.replace("\"", "'");

但最好将 ^ 放在字符串前面,这将是 :

 String s = "^" +"read \"book ^<init^> \"" ;

在命令中测试:

echo " read "book <init>""

echo  ^" read "book <init>""