[英]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.