2013-03-03 79 views
0

我有一個按鈕,我想要的是單擊該按鈕來執行bat文件背景,這會在文件夾中生成一個文件,並且Java窗口仍然存在。Java-在關閉Java窗口之前單擊按鈕時執行bat文件

但在我的代碼中,我需要關閉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); 

回答

0

您應該使用的確以下代碼:

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(); 
} 
+0

謝謝!你的代碼非常適用於一件小事。它說這裏是一個錯誤 process.waitFor(); 我刪除它然後就可以了。你知道爲什麼嗎? – 2013-03-03 20:20:25

+0

@嘉亞國我很高興。 :)。那是什麼特殊情況? – 2013-03-03 20:22:00

+0

@JayayiGuo:Process.waitFor()拋出'InterruptedException'。如果你還沒有發現,那麼它會導致編譯時錯誤。這就是爲什麼我把你的代碼中捕獲到的異常改爲「Exception」.. !!此語句對分析過程是否成功執行非常有用,因此在代碼中包含這些行是MHO。 – 2013-03-03 20:30:48

1

你不應該使用在Runtime.getRuntime.exec()參數start說法。它導致打開一個執行指定命令的新窗口。

這應該工作

Runtime.getRuntime().exec("cmd.exe /C C:\\SUMO\\bin\\OSMTEST.bat");