Reputation: 301
In this question it shows that when you run a shell command from Java, it runs from the current directory. When I run the command javac Program.java
from my program, it shows the error (from the standard error stream):
javac: file not found: Program.java
Usage: javac <options> <source files>
use -help for a list of possible options
However, when I run the same exact command from the actual Terminal, it works fine and saves the .class file in the default directory. This is the code:
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();
Any ideas why it works when I type it in the actual Terminal, but not when I run it from my program? I am running a Max OS X Mountain Lion (10.6)
Thanks
Upvotes: 1
Views: 977
Reputation: 301
The reason my code was not working was because I was running it in Eclipse IDE, and that messes up the directory the program is running from. To fix that program, I changed the command to javac -d . src/Program.java
. If I export the program into a .jar
file and run it in the desktop, my original command will do just fine.
Thanks to saka1029 for helping me!
Upvotes: 1
Reputation: 9576
Your program is probably being run from a different directory. Your IDE (such as Eclipse) is probably is running from one location, and knows the directory structure to access your program files.
The easiest, quickest solution is to just write the fully-qualified file path for Program.java
.
The alternate is to find out what the current directory is. So, perhaps run pwd
the same way you are running javac Program.java
from within your program's code? Then you can see what directory your program is actually being run from. Once you know that, you can write the appropriate directory structure.
For example, if pwd
reveals that you are actually 2 directories above where Program.java
is, then you can put those directories in the command like this: javac ./dir1/dir2/Program.java
.
To change the directory Eclipse runs from, see this question Set the execution directory in Eclipse?
Upvotes: 1
Reputation: 59
You can try to print the path in your programm ,use new File(".").getAbsolutePath() ,if you are in a ide ,the path may be in the root of the project rather than in the path of the current java file
Upvotes: 1