When Runtime.getRuntime (). Exec call linux batch file could not find its physical directory
I have a java application. And I am using Runtime.getRuntime (). exec to invoke a batch file. When I call a linux batch file using Runtime.getRuntime (). exec, the batch file could not find its own directory, I am using the pwd command in the batch file, but it returns the application path. I need my own physical path for the batch file. How can i do this?
source to share
You must use ProcessBuilder to accomplish this:
ProcessBuilder builder = new ProcessBuilder( "pathToExecutable");
builder.directory( new File( "..." ).getAbsoluteFile() ); //sets process builder working directory
source to share
Try it. It works 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();
source to share
Batch files , if you specifically refer to files with the ".bat" extension, are intended to be used with the Microsoft shell command line ('cmd.exe') on Windows, as they are script files containing a sequence of commands specifically for that shell, and how it won't work with Unix shells such as Bash.
Assuming you actually mean a Unix shell script 'and not just a Microsoft batch file, you are better off using ProcessBuilder as it provides more flexibility than the Runtime method exec()
.
To use ProcessBuilder to run a script in its own directory, set the builder directory to the same directory you use to point to the script, for example:
// 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();
source to share