Java Runtime.exec 在 Linux 中因空间而失败

标签 java linux command-line exec

我搜索了很多,但没有找到解决方案。 我的目标是在 windows 和 linux 中使用 java 调用命令并获取输出。我找到了 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"};
}

关于Java Runtime.exec 在 Linux 中因空间而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51173961/

相关文章:

java - spring boot jdbc 连接

java - 第二个带注释的方面未被调用

java.io.FileNotFoundException :/storage/emulated/0/New file. txt:打开失败:EACCES(权限被拒绝)

Java:如何获取可以到达远程IP的本地接口(interface)的IP?

linux - PubKey SSH Auth 在 CentOS 上失败,但在 Ubuntu 上有效

javascript - 重复输出到控制台 - 我必须在哪里插入我的回调?

linux - 获取所有目录逗号分隔并将输出发送到其他脚本

linux - bash 脚本 - 循环中的 2 个变量

c - 在 C 中通过命令行传递整数?

windows - powershell 2.0重定向文件句柄异常