2013-03-03 72 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");