I've seen some examples of how to "execute" CMD commands by the application, though, I'm facing some difficulties. What I am trying to do is to give a cd
in the oracle folder, and then run Backup.exe
, and "set" in JTextArea
the cmd log. However, I'm not having a comeback.
Can anyone give me a targeting?
Note: I did not put the share of the Backup.exe
bat in the way, since I still could not access the directory.
import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CmdTest extends JFrame {
private JTextField diretorio = new JTextField();
private JTextArea log = new JTextArea();
private JButton jButton = new JButton("Executar");
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new CmdTest();
});
}
public CmdTest() {
setTitle("Teste CMD");
add(painel());
pack();
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
diretorio.setText("C:/oraclexe/app/oracle/product/11.2.0/server/bin");
}
private JPanel painel() {
JPanel painel = new JPanel();
painel.setLayout(new BorderLayout());
painel.add(diretorio, BorderLayout.NORTH);
painel.add(log, BorderLayout.CENTER);
painel.add(jButton, BorderLayout.SOUTH);
diretorio.setPreferredSize(new Dimension(400, 20));
log.setPreferredSize(new Dimension(400, 90));
action();
return painel;
}
private void action() {
jButton.addActionListener(e -> {
performBackup();
});
}
private void performBackup() {
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "cd " + diretorio.getText());
builder.redirectErrorStream(true);
Process p = null;
try {
p = builder.start();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while (true) {
try {
line = r.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (line == null) {
break;
}
System.out.println(line);
}
}
}