java - 在 java 代码中运行 .exe 文件

标签 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);
    }

}

最佳答案

尝试传递绝对路径

例子

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

关于java - 在 java 代码中运行 .exe 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17364820/

相关文章:

c++ - 如何将 C++ 对象传递给 NPAPI 插件?

mysql - 无法远程连接到在 Windows 上运行的 MySQL (TCP/IP)

windows - 如何在 Qt 中为堆叠小部件使用动画?

visual-studio-2012 - 路径中存在非法字符

java - 扩展 BaseAdapter 的 ApkAdapter 类的 getView 方法中的 NullPointerException

java 引用 Class<> 作为其子类型

java - Java 泛型接口(interface)

sql - 使 SSMS 启动并连接到数据库的 URL?

windows - 应用程序从批处理文件中按顺序启动

java - 在 Eclipse RCP 中,如何根据编辑器中的 "dirty"属性禁用保存工具栏按钮