Java Runtime.exec在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]# 

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


函数式编程
浏览 252回答 1
1回答

郎朗坤

有两个版本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"};}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java