繁体   English   中英

Java Runtime.exec在Linux中空间不足时失败

[英]Java Runtime.exec fail with space in linux

我搜索了很多,但没有找到解决方案。 我的目标是使用Java调用命令并在Windows和Linux中获取输出 我找到了Runtime.exec方法并做了一些实验。 一切正常,除非命令参数中有空格。 测试代码如下,同样在github中
该代码在Windows上运行良好,但在Linux中,输出为空:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
public static void main(String[] args) {
    try {
        Runtime rt = Runtime.getRuntime();
        String[] commandArray;
        if (isWindows()) {
            commandArray = new String[]{"cmd", "/c", "dir", "\"C:\\Program Files\""};
        } else {
            commandArray = new String[]{"ls", "\"/root/a directory with space\""};
        }
        String cmd = String.join(" ",commandArray);
        System.out.println(cmd);

        Process process = rt.exec(commandArray);
        BufferedReader input = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
        String result = "";
        String line = null;
        while ((line = input.readLine()) != null) {
            result += line;
        }
        process.waitFor();
        System.out.println(result);

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

public static boolean isWindows() {
    String OS = System.getProperty("os.name").toLowerCase();
    return (OS.indexOf("win") >= 0);
    }
}

如果我直接在bash中执行打印的命令,则输出是预期的。

[root@localhost javatest]# javac Main.java 
[root@localhost javatest]# java Main
ls "/root/a directory with space"

[root@localhost javatest]# ls "/root/a directory with space"
a.txt  b.txt
[root@localhost javatest]# 

谁能解释原因并给出解决方法?

exec有两个版本。

  • exec(String command)

    在这里,您可以通过与在命令行上执行命令类似的方式来指定命令,即,您需要用空格将引号引起来。

     cmd /c dir "C:\\Program Files" 
  • exec(String[] cmdarray)

    在这里,您分别指定参数,因此参数按原样给出,即不带引号。 exec方法将处理参数中的所有空格和引号字符,并根据需要正确引用和转义参数以执行命令。

     cmd /c dir C:\\Program Files 

因此,删除添加的多余引号:

if (isWindows()) {
    commandArray = new String[] { "cmd", "/c", "dir", "C:\\Program Files"};
} else {
    commandArray = new String[] { "ls", "/root/a directory with space"};
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM