Reputation: 145
This is my code:
import java.io.IOException;
public class testv1 {
public static void main (String[] args) {
System.out.println("ABC");
try {
Process proc = Runtime.getRuntime()
.exec("D:\\Program\\Pyinstaller\\Merge\\Test\\dist\\helloworld.exe");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
I want to run helloworld.exe but it's not working. The program is just printing
ABC
DONE
I also tried this:
import java.io.File;
import java.io.IOException;
public class testv1 {
public static void main (String[] args) {
System.out.println("ABC");
try
{
Runtime.getRuntime().exec("D:\\Program\\Pyinstaller\\Merge\\Test\\dist\\helloworld.exe", null, new File("D:\\Program\\Pyinstaller\\Merge\\Test\\dist\\"));
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("Done");
}
}
but same output as the previous one.
Upvotes: 0
Views: 1424
Reputation: 106
You can execute a process using a working directory:
exec(String command, String[] envp, File dir)
Executes the specified string command in a separate process with the specified environment and working directory.
command is the location of the .exe envp can be null dir, is the directory of your .exe With respect to your code it should be...
Runtime.getRuntime().exec("c:\\program files\\test\\test.exe", null, new File("c:\\program files\\test\\"));
You can use Runtime.exec(java.lang.String, java.lang.String[], java.io.File) where you can set the working directory.
Or else you can use ProcessBuilder as follows:
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
pb.directory(new File("myDir"));
Process p = pb.start();
For reading output from process:
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
Upvotes: 1