程序是这样的,使用一个java程序调用另外一个java程序,在调用时需要填入带空格的参数,我在这种参数外用双引号,在windows下可以正常运行。但是转到linux下,发现调用程序解析参数仍然用空格分割了参数,改为单引号也不行。奇怪的是,将调用的命令行在终端执行的时候,却可以正常运行。求解???

解决方案 »

  1.   

    have a try
    String cmd = "java your_other_class \" \" your_param2...";
    System.out.println(cmd);
    Runtime.getRuntime().exec(cmd);
      

  2.   

    在程序里面,我就是这么写的。问题是,我将print的内容直接复制到终端上是可以运行的,在windows里面也可以运行,在linux就不行了。因为我试过输入不带空格的参数,没问题,所以我想问题还是出在参数的空格上。
      

  3.   

    以前我也遇到过类似的问题,当时怎么解决的现在忘了
    可不可以这样,先写到临时文件,执行完了再删除临时文件
    String[] cmds = {
        "echo #/bin/bash > tempExec.sh",
        "echo java xxx \" \" param2... >> tempExec.sh",
        "chmod 755 tempExec.sh",
        "./tempExec.sh",
        "rm tempExec.sh"
    };
    Runtime.getRuntime().exec(cmds);
      

  4.   

    那你可以把命令分开执行
    String[] cmds = { 
        "echo #/bin/bash  > tempExec.sh", 
        "echo java xxx \" \" param2...  > > tempExec.sh", 
        "chmod 755 tempExec.sh"
    }
    Runtime.getRuntime().exec(cmds);String cmd = "./tempExec.sh";
    Process p = Runtime.getRuntime().exec(cmd);
    //do something herecmd = "rm tempExec.sh";
    Process p = Runtime.getRuntime().exec(cmd);
      

  5.   

    还是不行,试了一下,根本通过这种命令产生不了shell脚本。
      

  6.   

    应该不会产生不了脚本的,可能是时间问题
    String[] cmds = {  
        "echo #/bin/bash   > tempExec.sh",  
        "echo java xxx \" \" param2...   >  > tempExec.sh",  
        "chmod 755 tempExec.sh" 

    Process p = Runtime.getRuntime().exec(cmds); 
    //这里有必要等待
    p.waitFor();String cmd = "./tempExec.sh"; 
    Process p = Runtime.getRuntime().exec(cmd); 
    //do something here 
    //这里也有必要等待cmd = "rm tempExec.sh"; 
    Process p = Runtime.getRuntime().exec(cmd); //等待的时候注意死锁,应该要手工清空p.getInputStream()的buffer,那要写一个线程了,好像问题就复杂化了
    以下是javadoc里的一段话,倒数一句说明了死锁的理由。
    The methods that create processes may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (getOutputStream(), getInputStream(), getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock或者你用某个特殊符号代替空格参数,然后在java里进行判断,如果是这个特殊符号的就转成空格处理。这样会不会好一些。