Java – 使用选项执行程序,如ls -l

  1. 在Java中,如何使用选项执行linux程序,如下所示:

    ls -a (选项是-a),

    另一个: ./myscript name=john age=24

    我知道如何执行命令,但不能执行该选项。

你需要执行一个外部进程,看看ProcessBuilder ,只是因为它几乎回答你的问题, 使用ProcessBuilder进行系统调用

用例子更新

我直接从列表示例中删除了它并对其进行了修改,以便我可以在我的PC上进行测试并且运行正常

 private static void copy(InputStream in, OutputStream out) throws IOException { while (true) { int c = in.read(); if (c == -1) { break; } out.write((char) c); } } public static void main(String[] args) throws IOException, InterruptedException { // if (args.length == 0) { // System.out.println("You must supply at least one argument."); // return; // } args = new String[] {"cmd", "/c", "dir", "C:\\"}; ProcessBuilder processBuilder = new ProcessBuilder(args); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); copy(process.getInputStream(), System.out); process.waitFor(); System.out.println("Exit Status : " + process.exitValue()); } 

Apache Commons有一个用于处理此类事情的库。 在我用手编写类似的东西之前,我希望我知道它。 我后来发现了。 它为命令行程序采用各种格式的选项。

Apache Commons CLI