How to run and display CMD log?

Asked

Viewed 755 times

2

I have seen some examples of how to "execute" CMD commands, by the application, however, I am facing some difficulties. What I’m trying to do is give a cd in the oracle folder, and then run the Backup.exe, and "set" in the JTextArea cmd log. However, I’m not getting any feedback.

Can someone give me a direction?

Note: I did not put in the way the part of running the bat Backup.exe, because I haven’t been able to access the directory yet.

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);
        }
    }
}
  • @Articuno I tried to follow, but I couldn’t

  • The way it is, I managed to copy the log to the textarea without problems. I think Voce can not give cd, pass the direct file path, cd will not work, at least in the tests I did it was useless to list the directory.

  • 1

    If the goal is only to execute the . exe, it is not necessary to enter the directory, just call the exe with the full path, for example: C:/oraclexe/app/oracle/product/11.2.0/server/bin/Backup.exe

  • @Even taking CD, it still doesn’t work. Can you show me how you did ?

  • @Gustavosantos already tested the solution of the peter?

  • @Article yes, it returns me java.lang.Exception: 'C:/oraclexe/app/oracle/product/11.2.0/server/bin' n o recognized as an internal & #Xa; or external command, an Oper able program or a batch file.

  • 1

    @Gustavosantos I tested Pedro’s solution and it is functional. Just pass the complete file path to his method. If you are making a mistake, the problem is something else not mentioned in the code or in the question,

Show 3 more comments

1 answer

0

Follows a generic method, where you pass the command, in your case, the full path + the name of the executable, and it returns a string with the result of the process.

/**
 * Executa um comando no CMD.
 * @param comando
 * @return a string de retorno do comando passado por paramêtro
 * @throws Exception caso o comando retore um código de erro
 */
public String executa(String comando) throws Exception {

    StringBuilder standartOutput = new StringBuilder();
    StringBuilder errorOutput = new StringBuilder();
    int exitStatus;

    Runtime rt = Runtime.getRuntime();
    Process proc;

    proc = rt.exec("cmd.exe /C SET \"NOPAUSE=true\" && " + comando);

    exitStatus = proc.waitFor();

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

    BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

    String s;

    while ((s = stdInput.readLine()) != null) {
        standartOutput.append(s);
        standartOutput.append("\n");
    }

    while ((s = stdError.readLine()) != null) {
        errorOutput.append(s);
        errorOutput.append("\n");
    }

    if (exitStatus != 0 || !errorOutput.toString().isEmpty()) {
        throw new Exception(standartOutput + "\n" + errorOutput);
    }

    return standartOutput.toString();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.