需要帮助才能找到文件名

时间:2011-07-02 15:25:59

标签: java exe runtime.exec

我使用以下代码来运行我通过代码加载的exe。

private static String filelocation = "";

  load_exe.addActionListener(new ActionListener() {

     @Override
     public void actionPerformed(ActionEvent e) {
        try {
           JFileChooser file_Choose = new JFileChooser();

           file_Choose.showOpenDialog(frame);
           JavaSamp.filelocation = file_Choose.getCurrentDirectory()
                    .toString()
                    + "\\" + file_Choose.getSelectedFile().getName();
           System.out.println("FileLocation" + JavaSamp.filelocation);
        } catch (Exception expobj) {
           // TODO Auto-generated catch block
        }
        Runtime rt = Runtime.getRuntime();

        try {
           System.out.println("File Run Location" + JavaSamp.filelocation);
           proc = rt.exec(JavaSamp.filelocation);

        } catch (IOException e4) {
           e4.printStackTrace();
        } catch (Exception e2) {

        }
     }
  });

我的问题是,上面执行的JavaSamp.filelocation应该多次完成。第一次只加载exe。下次我不会。我需要将exe存储在一个字符串中以便连续运行。 任何建议请

1 个答案:

答案 0 :(得分:0)

如果您想要记住使用过的文件,只需使用null初始化filelocation并测试它。顺便说一句:将它存储为File更有意义,构建绝对路径的方式有点错综复杂 - 与仅调用getAbsolutePath()

相比
private static File filelocation = null;

private static void test() {
    load_exe.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            // Check if file-name to execute has already been set
            if (filelocation != null) {
                try {
                    JFileChooser file_Choose = new JFileChooser();

                    file_Choose.showOpenDialog(frame);
                    JavaSamp.filelocation = file_Choose.getSelectedFile();
                    System.out.println("FileLocation"
                            + JavaSamp.filelocation.getAbsolutePath());
                } catch (Exception expobj) {
                }
            }
            Runtime rt = Runtime.getRuntime();

            try {
                System.out.println("File Run Location"
                        + JavaSamp.filelocation.getAbsolutePath());
                Process proc = rt.exec(JavaSamp.filelocation
                        .getAbsolutePath());

            } catch (IOException e4) {
                e4.printStackTrace();
            }
        }
    };
}