在Java代码中运行.exe文件 [英] Running a .exe file inside java code

查看:88
本文介绍了在Java代码中运行.exe文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行在Java代码中生成的.exe文件。我有一个用Java编写的GUI,.exe文件是使用MATLAB(实际上是Simulink模型)生成的。当我分别运行.exe文件时(即,我双击它),它将创建一个输出文件(这是我期望的),但是当我运行Java代码时,它将打开命令提示符,但不会在该位置生成任何输出全部-实际上,我什至不知道它是否运行我的.exe文件。

I am trying to run a .exe file that I have generated inside a Java code. I have a GUI written in Java and the .exe file is generated using MATLAB (its actually a Simulink model). When I run the .exe file separately (i.e. I double click on it) it will create an output file ( which is what I expect) but when I run my Java code it opens the command prompt but it won't generate any outputs at all -in fact I am not even sure if it runs my .exe file or not.

这是我的代码:

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

}


推荐答案

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

尝试此操作

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

这篇关于在Java代码中运行.exe文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆