Reputation: 103
I have a button, what I want is to click the button to execute a bat file background, which will generate a file in a folder, and the Java window remains there.
But in my code, I need to close the Java window to get the bat file executed.
Would you please help to check where I need to change?
I don't need to see the bat screen. Thanks!
final JButton importMap = new JButton("Import");
importMap.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg1) {
//String osm = osmFile_path.replaceAll("\\","\\\\");
System.out.println("You are going to import:"+osmFile_path);
//Runtime.getRuntime().exec()
try {
FileWriter fw2 = new FileWriter("C:\\SUMO\\bin\\OSMTEST.bat");
fw2.write("@echo off");
fw2.write("\r\n");
fw2.write("cmd");
fw2.write("\r\n");
fw2.write("set default_dir=C:\\SUMO\\bin");
fw2.write("\r\n");
fw2.write("start /b C:\\SUMO\\bin\\netconvert --osm-files="+osmFile_path+" --output-file="+osmnet_file);
fw2.close();
Runtime.getRuntime().exec("cmd.exe /C start /b C:\\SUMO\\bin\\OSMTEST.bat");
} catch(IOException e) {
e.printStackTrace();
}
}
});
content.add(importMap);
Upvotes: 0
Views: 1540
Reputation: 13066
You should use the following code indeed:
try {
FileWriter fw2 = new FileWriter("C:\\SUMO\\bin\\OSMTEST.bat");
fw2.write("@echo off");
fw2.write("\r\n");
//fw2.write("cmd");//No need to specify this line
fw2.write("\r\n");
fw2.write("set default_dir=C:\\SUMO\\bin");
fw2.write("\r\n");
fw2.write("start /b C:\\SUMO\\bin\\netconvert --osm-files="+osmFile_path+" --output-file="+osmnet_file);
fw2.write("\r\n");
fw2.write("Exit");//To close bat file
fw2.write("\r\n");
fw2.close();
Process process = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "C:\\SUMO\\bin\\OSMTEST.bat");//use the protoclhandler
process.waitFor();//Waits the process to terminate
if (process.exitValue() == 0)
{
System.out.println("Process Executed Successfully");
}
} catch(Exception e) {//Process.waitFor() can throw InterruptedException
e.printStackTrace();
}
Upvotes: 0
Reputation: 3511
You should not use the start
argument in the Runtime.getRuntime.exec()
parameters. It causes to open a new window for executing the specified command.
This should work
Runtime.getRuntime().exec("cmd.exe /C C:\\SUMO\\bin\\OSMTEST.bat");
Upvotes: 1