Java Shell命令未从当前目录运行



在这个问题中,它显示了当您从Java运行shell命令时,它从当前目录运行。当我从程序中运行命令javac Program.java时,它显示错误(来自标准错误流):

javac: file not found: Program.java
Usage: javac <options> <source files>
use -help for a list of possible options

但是,当我从实际的终端运行相同的命令时,它运行良好,并将.class文件保存在默认目录中。这是代码:

Runtime rt = Runtime.getRuntime();
String command = "javac Program.java";
Process proc = rt.exec(command);
BufferedReader stdInput = new BufferedReader(new 
     InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new 
     InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:n");
String s = null;
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):n");
while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}
proc.waitFor();

有什么想法吗?为什么当我在实际的终端中键入它时它有效,而当我从程序中运行它时却无效?我正在运行Max OS X Mountain Lion(10.6)

感谢

您可以尝试在程序中打印路径,使用new File(".").getAbsolutePath(),如果您在ide中,路径可能在项目的根目录中,而不是在当前java文件的路径中

您的程序可能是从不同的目录运行的。您的IDE(如Eclipse)可能在一个位置运行,并且知道访问程序文件的目录结构。

最简单、最快捷的解决方案是只为Program.java编写完全限定的文件路径。

另一种方法是找出当前目录。所以,也许可以像在程序代码中运行javac Program.java一样运行pwd?然后您可以看到您的程序实际上是从哪个目录运行的。一旦知道了这一点,就可以编写适当的目录结构。

例如,如果pwd显示您实际上在Program.java所在的位置上方有两个目录,那么您可以将这些目录放在命令中,如下所示:javac ./dir1/dir2/Program.java

要更改Eclipse运行的目录,请参阅此问题在Eclipse中设置执行目录?

我的代码不工作的原因是我在Eclipse IDE中运行它,这会打乱程序运行的目录。为了修复该程序,我将命令更改为javac -d . src/Program.java。如果我将程序导出到.jar文件中并在桌面上运行,我原来的命令会很好。

感谢saka1029的帮助!

最新更新