Java Runtime.getRuntime()。exec()无法按预期工作

时间:2019-01-16 20:33:02

标签: java

我正在尝试使用方法Runtime.getRuntime().exec()执行命令,但是它不起作用。在终端中,一切正常,

有问题的命令如下:

gcc ~/library/build/*.o -o ~/library/build/application -L ~/library/build -lpstr

我的测试代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) {
        try {
            String cmd =
                    "gcc ~/library/build/*.o " +
                            "-o ~/library/build/application " +
                            "-L ~/library/build -lpstr";
            System.out.println(String.format("Command: \"%s\"", cmd));
            Process p = Runtime.getRuntime().exec(cmd);

            BufferedReader std = new BufferedReader(new InputStreamReader(p.getInputStream()));
            BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            p.waitFor();

            String message;

            System.out.println("Standard output:");
            while ((message = std.readLine()) != null)
                System.out.println(message);

            System.out.println("Error output:");
            while ((message = err.readLine()) != null)
                System.out.println(message);

            System.exit(0);
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        }
    }
}

测试代码输出:

Command: "gcc ~/library/build/*.o -o ~/library/build/application -L ~/library/build -lpstr"
Standard output:
Error output:
gcc: error: ~/library/build/*.o: No such file or directory

端子测试:

michael@MICHAEL-PC:~/library$ tree
.
├── build
│   ├── libpstr.a
│   ├── main.o
│   └── util.o
├── main.c
├── util.c
└── util.h

1 directory, 6 files
michael@MICHAEL-PC:~/library$ gcc ~/library/build/*.o -o ~/library/build/application -L ~/library/build -lpstr
michael@MICHAEL-PC:~/library$ tree
.
├── build
│   ├── application
│   ├── libpstr.a
│   ├── main.o
│   └── util.o
├── main.c
├── util.c
└── util.h

1 directory, 7 files
michael@MICHAEL-PC:~/library$

0 个答案:

没有答案