I have an java application.And I use Runtime.getRuntime().exec for call a batch file.When I call a linux batch file using with Runtime.getRuntime().exec the batch file could not find its own directory. I use pwd command in batch file but it returns application path. I need batch file's own physical path from itself. How can I do this?
-
1You should use `$0` rather than `pwd` but that’s not in any way related to Java. It might be even belong to http://superuser.com/ rather than stackoverflow. – Holger Aug 20 '14 at 11:45
-
`batch` file for `Linux` is generally called `script` in Linux! – Am_I_Helpful Aug 20 '14 at 11:45
-
or if you want to change the working dir look at http://stackoverflow.com/questions/6811522/changing-the-working-directory-of-command-from-java – mwerschy Aug 20 '14 at 11:46
-
http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in – Holger Aug 20 '14 at 11:53
3 Answers
You must use a ProcessBuilder in order to acomplish that:
ProcessBuilder builder = new ProcessBuilder( "pathToExecutable");
builder.directory( new File( "..." ).getAbsoluteFile() ); //sets process builder working directory

- 1,861
- 1
- 15
- 23
Try this . Its working for me.
Process p = Runtime.getRuntime().exec("pwd");
BufferedReader bri = new BufferedReader
(new InputStreamReader(p.getInputStream()));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p.getErrorStream()));
String line;
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
p.waitFor();

- 1,983
- 3
- 14
- 26
Batch files, if you're specifically referring to files with the '.bat' extension, are designed to be used with Microsoft's Command Prompt shell ('cmd.exe') in Windows, as they are script files containing a sequence of commands specifically for this shell, and as such will not work with Unix shells such as Bash.
Assuming you actually mean a Unix 'shell script', and not specifically a Microsoft 'batch file', you'd be better off using the ProcessBuilder class, as it provides greater flexibility than Runtime's exec()
method.
To use ProcessBuilder to run a script in its own directory, set the builder's directory to the same directory that you're using to point to the script, like so:
// Point to wherever your script is stored, for example:
String script = "/home/andy/bin/myscript.sh";
String directory = new File(script).getParent();
// Point to the shell that will run the script
String shell = "/bin/bash";
// Create a ProcessBuilder object
ProcessBuilder processBuilder = new ProcessBuilder(shell, script);
// Set the script to run in its own directory
processBuilder.directory(new File(directory));
// Run the script
Process process = processBuilder.start();

- 45
- 6