简体   繁体   中英

Java Runtime.exec fail with space in linux

I searched a lot but did not find the solution. My goal is using java to call commands and get output in windows and linux . I found Runtime.exec method and did some experiments. Everything went ok except when there's space in the command parameters. Test code as below, also in github .
The code works well on windows, but in linux, output is empty:

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);
    }
}

if I execute the printed command in bash directly, then the output is as expected.

[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]# 

Can anyone explain why and give ways to solve?

There are two versions of exec .

  • exec(String command)

    Here you specify a command in a similar way to how you would do it on the command-line, ie you need to quote arguments with spaces.

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

    Here you specify the arguments separately, so the arguments are given as-is, ie without quotes. The exec method will take care of any spaces and quote-characters in the argument, correctly quoting and escaping the argument as needed to execute the command.

     cmd /c dir C:\\Program Files 

So, remove the extra quotes you added:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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