-1

我有一个 bat 文件来转储数据库。我想用 java 执行它,我想使用 JFileChooser 添加该转储位置。可能吗?

提前致谢

4

1 回答 1

0

是的,当然有可能。编写您的批处理,以便它接受一个参数 - 转储路径。

然后使用 JFileChooser 选择文件夹位置并在 Java 应用程序中执行批处理文件。以下代码将创建一个带有两个按钮的框架 - 一个选择目录并将绝对路径连接到命令字符串,另一个按钮执行您的批处理。

public class DBDumpExec {

private static final String batchCMD = "myBatch.bat";
public static String directoryChosen = "";

public static void main(String[] args) {
    final JFrame frame = new JFrame("DB Dump Executor");
    frame.setSize(450, 150);
    Container content = frame.getContentPane();
    content.setLayout(new GridLayout(3, 1, 5, 5));

    // Display directory label
    final JLabel directoryLabel = new JLabel();
    // Button to open Dialog
    JButton openDialogButton = new JButton("Open Dialog");
    openDialogButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            JFileChooser chooser = new JFileChooser();
            chooser.setDialogTitle("Select target dump directory");
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            File myFile;
            int returnVal = chooser.showOpenDialog(frame);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                myFile = chooser.getSelectedFile();
                directoryChosen = myFile.getAbsolutePath();
                directoryLabel.setText(directoryChosen + " chosen!");
                System.out.println(myFile.getAbsolutePath());
            }
        }
    });
    // Click this button to run the batch
    JButton executorButton = new JButton("Execute DB");
    executorButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            // Run batch
            try {
                Process process = Runtime.getRuntime().exec(
                        batchCMD + " " + directoryChosen);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    content.add(openDialogButton);
    content.add(directoryLabel);
    content.add(executorButton);
    frame.setVisible(true);
  }
}

从Runtime Javadoc阅读有关执行命令的更多信息。

于 2013-03-29T16:20:22.913 回答