在java代码中运行.exe文件

时间:2013-06-28 12:32:44

标签: java windows cmd exe

我正在尝试运行我在Java代码中生成的.exe文件。我有一个用Java编写的GUI,而.exe文件是使用MATLAB生成的(它实际上是一个Simulink模型)。当我单独运行.exe文件(即我双击它)时,它将创建一个输出文件(这是我所期望的)但是当我运行我的Java代码时它会打开命令提示符,但它不会生成任何输出所有 - 事实上我甚至不确定它是否运行我的.exe文件。

这是我的代码:

package combustionModel;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class GUIInterface extends JFrame {  
    JButton b1 = new JButton();

    public static void main(String[] args){
        GUIInterface gui = new GUIInterface();  
    }

    static class Action implements ActionListener{
        public void actionPerformed (ActionEvent e){
            JFrame frame2 = new JFrame();
            frame2.setVisible(true);
            frame2.setSize(100, 200);
            final JFileChooser fc  = new JFileChooser();
            fc.showOpenDialog(null);
            File file = fc.getSelectedFile();
            System.out.println(file.getAbsolutePath());
            try {
                Runtime runtime = Runtime.getRuntime();
                Process p = Runtime.getRuntime().exec("cmd /c start "+file.getAbsolutePath());
                p.waitFor();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }

    public GUIInterface(){
        setVisible (true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400,200);
        setLayout(new FlowLayout());
        JPanel adpanel = new JPanel();
        JButton OK = new JButton();
        b1.addActionListener(new Action());
        adpanel.add(OK);
        adpanel.add(b1);
        super.add(adpanel);
    }

}

2 个答案:

答案 0 :(得分:1)

尝试传递绝对路径

示例

Runtime.getRuntime().exec("c:\\program files\\test\\test.exe", null, new File("c:\\program files\\test\\"));

答案 1 :(得分:1)

 Process p = Runtime.getRuntime().exec("cmd /c "+file.getAbsolutePath());

试试这个

 Process p = Runtime.getRuntime().exec("cmd /c start "+file.getAbsolutePath());