[英]Java-Execute bat file when clicking button, before closing the Java window
我有一个按钮,我想要单击该按钮以执行bat文件背景,这将在文件夹中生成文件,并且Java窗口保留在那里。
但是在我的代码中,我需要关闭Java窗口才能执行bat文件。
您能帮我检查一下我需要更改的地方吗?
我不需要看蝙蝠屏幕。 谢谢!
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);
您不应在Runtime.getRuntime.exec()
参数中使用start
参数。 这将导致打开一个用于执行指定命令的新窗口。
这应该工作
Runtime.getRuntime().exec("cmd.exe /CC:\\\\SUMO\\\\bin\\\\OSMTEST.bat");
您确实应该使用以下代码:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.