如何从 Java 调用 Linux shell 命令

2022-08-31 10:28:47

我正在尝试使用重定向(>&)和管道(|)从Java执行一些Linux命令。Java 如何调用 或 命令?cshbash

我试图使用这个:

Process p = Runtime.getRuntime().exec("shell command");

但它与重定向或管道不兼容。


答案 1

exec 不会在 shell 中执行命令

尝试

Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});

相反。

编辑::我的系统上没有csh,所以我用bash代替了。以下内容对我有用

Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});

答案 2

使用 ProcessBuilder 分隔命令和参数,而不是空格。无论使用何种 shell,这应该有效:

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(final String[] args) throws IOException, InterruptedException {
        //Build command 
        List<String> commands = new ArrayList<String>();
        commands.add("/bin/cat");
        //Add arguments
        commands.add("/home/narek/pk.txt");
        System.out.println(commands);

        //Run macro on target
        ProcessBuilder pb = new ProcessBuilder(commands);
        pb.directory(new File("/home/narek"));
        pb.redirectErrorStream(true);
        Process process = pb.start();

        //Read output
        StringBuilder out = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null, previous = null;
        while ((line = br.readLine()) != null)
            if (!line.equals(previous)) {
                previous = line;
                out.append(line).append('\n');
                System.out.println(line);
            }

        //Check result
        if (process.waitFor() == 0) {
            System.out.println("Success!");
            System.exit(0);
        }

        //Abnormal termination: Log command parameters and output and throw ExecutionException
        System.err.println(commands);
        System.err.println(out.toString());
        System.exit(1);
    }
}

推荐