我有一个bat文件来转储数据库。我想用java执行它,我想使用JFileChooser添加该转储位置。有可能吗?
先谢谢
答案 0 :(得分: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执行命令的更多信息。