我最近一直在开发一个程序,它可以从 Java 程序编译和运行 C++ 程序,基本上一切正常(或者至少据我所知),但后来我注意到一些东西被打印到错误流中:
cdog5000@srv3:~$ java -Xmx50m -jar main2.jar
Running Command: sudo g++ --static -o "/home/cdog5000/cody.out" "/home/cdog5000/cody.cpp"
Err: g++: "/home/cdog5000/cody.cpp": No such file or directory
Err: g++: no input files
cdog5000@srv3:~$ ls -l
total 4548
-rwxr-xr-x 1 cdog5000 cdog5000 1297588 Feb 3 23:11 a.out
-rwxr-xr-x 1 cdog5000 cdog5000 7978 Feb 2 04:39 cody
-rw-r--r-- 1 cdog5000 cdog5000 106 Feb 4 02:09 cody.cpp
-rwxr-xr-x 1 cdog5000 cdog5000 1297357 Feb 4 02:09 cody.out
-rw-r--r-- 1 root root 410433 Feb 4 02:48 log.txt
-rwxr-xr-x 1 cdog5000 cdog5000 801088 Feb 1 05:24 main.jar
-rw-r--r-- 1 cdog5000 cdog5000 804802 Feb 4 02:49 main2.jar
drwxr-xr-x 3 cdog5000 cdog5000 4096 Feb 3 23:11 sandbox
cdog5000@srv3:~$ sudo g++ --static -o "/home/cdog5000/cody.out" "/home/cdog5000/cody.cpp"
如您所见,如果我通过 SSH 而不是 Java 代码,它会起作用吗?
Java代码:
public static Exec exec(String cmd){
Exec exec = new Exec(cmd);
try {
long current = System.currentTimeMillis();
Process proc = Runtime.getRuntime().exec(cmd);
exec.setReturnValue(proc.waitFor());
exec.setRunTime(System.currentTimeMillis() - current);
BufferedInputStream bos = new BufferedInputStream(proc.getInputStream());
byte b[] = new byte[1024];
String content = "";
while(bos.read(b) != -1) {
content += new String(b);
}
exec.setStdIn(content.split("\n"));
content = "";
bos = new BufferedInputStream(proc.getErrorStream());
while(bos.read(b) != -1) {
content += new String(b);
}
exec.setStdErr(content.split("\n"));
} catch (Exception e) {
e.printStackTrace();
}
return exec;
}
感谢您的帮助,不胜感激!
最佳答案
Err: g++: "/home/cdog5000/cody.cpp": No such file or directory
告诉你问题所在。
你的一级引号太多,所以你正在寻找 "/home/cdog5000/cody.cpp"
而不是 /home/cdog5000/cody.cpp
.
More precisely, the command string is broken into tokens using a StringTokenizer created by the call new StringTokenizer(command) with no further modification of the character categories. The tokens produced by the tokenizer are then placed in the new string array cmdarray, in the same order.
这意味着它只在空格处拆分,它不像 shell 那样处理双引号。
许多语言都有两个函数,一个叫做 exec
,它逐字运行命令,另一个叫做 system
,它把字符串传递给 shell,在那里它会拆分单词和扩展通配符.
我在 Java 中看不到 system
调用,所以我认为您必须使用 exec(String[] cmdarray)
而不是 exec(字符串命令)
.
关于java - g++: 找不到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4893148/