[英]Java Runtime Execute different inside program than in command line?
我试图使用Runtime.getRuntime.exec(command)编译一些Java文件并生成命令。 下面的代码显示了我在做什么:
String command = "javac ";
for(String s: this.getPackages())
{
command = command + "/home/benuni/CompileFiles/" + project + "/" + s + "/*.java ";
}
try {
System.out.println("command: '"+ command +"'");
Process pro = Runtime.getRuntime().exec(command);
printLines(" stderr:", pro.getErrorStream());
pro.waitFor();
这给出了以下输出:
command: 'javac /home/benuni/CompileFiles/HelloWorldProject/HelloWorldPackage/*.java '
stderr: javac: file not found: /home/benuni/CompileFiles/HelloWorldProject/HelloWorldPackage/*.java
stderr: Usage: javac <options> <source files>
stderr: use -help for a list of possible options
并且它不起作用..但是,如果我将命令复制到我的shell中,则它没问题...有什么想法吗?
Java不会为您扩展*
通配符。 那是shell的功能。 相反,您需要列出目录以获取所有包含的文件。
像这样的东西将完成构建命令的技巧:
File[] files = new File("/home/benuni/CompileFiles/" + project + "/" + s).listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".java");
}
});
StringBuilder command = new StringBuilder("javac");
for(File file : files) {
command.append(" ").append(file.getAbsolutePath());
}
当您从命令行输入时,命令分析器会将*
扩展为文件列表。 当您使用Runtime.exec时,不会进行扩展,您必须显式指定整个列表。
一种选择是向javac提供文件名的实际列表。 另一个方法是使用以下命令让shell进行操作
/bin/sh -c javac /home/benuni/CompileFiles/HelloWorldProject/HelloWorldPackage/*.java
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.