Execute PROMPT / CMD commands in Java

Asked

Viewed 1,688 times

2

Good people, I would like to know how to execute this command in Java:

attrib -R -A -S -H /S /D I:\*.*

This program is to clean virus from flash drive. I have consulted some materials here in the forum, but I could not apply.

Basically the user will type the letter of your USB stick and click Run button, where will do the commands below.

String cmd, caminho,comando_01,comando_02;
        String[] executar;
        //************************************************
        cmd = "cmd /c"; // chamada para o cmd
        caminho = txtCaminhoTelaDois.getText() + ":"; //pegando caminho digitado
        comando_01 = "attrib -R -A -S -H /S /D" + caminho + "\\*.*";
        comando_02 = "del *.lnk";

        executar = new String[2];
        executar[0] = cmd + " " + caminho;
        executar[1] = cmd + " " + comando_02;

        //************************************************
        Runtime comando = Runtime.getRuntime();
        try {
            Process proc = comando.exec(executar);

            JOptionPane.showMessageDialog(null, "Concluído");
        }

        catch (IOException ex) {
            Logger.getLogger(TelaDois.class.getName()).log(Level.SEVERE, null, ex);

            JOptionPane.showMessageDialog(null, "Deu ruim...");
        }

2 answers

2

You are not changing the letter of the drive you are trying to access. First put this method below in your program for better reuse:

public String executar(String... comandos) {
  StringBuilder saida = new StringBuilder();
  BufferedReader leitor;
  ProcessBuilder processos;
  Process processo;

  try {
    processos = new ProcessBuilder("cmd.exe", "/c", String.join(" && ", comandos));
    processo = processos.start();
    processo.waitFor();
    leitor = new BufferedReader(new InputStreamReader(processo.getInputStream()));

    String linha = "";

    while ((linha = leitor.readLine()) != null) {
      saida.append(linha).append("\n");
    }
  } catch (IOException | InterruptedException ex) {
    return ex.getMessage();
  }

  return saida.toString();
}

Then in the call use:

this.executar("D:", comando_01, comando_02);

Or change your run to:

executar = new String[3];
executar[0] = "D:";
executar[1] = comando_01;
executar[2] = comando_02;
this.executar(executar);

Note that it is not necessary to pass the path of cmd. It is also important to note that you should pick up the letter from drive user-desired.

2

I think this place is wrong:

        comando_01 = "attrib -R -A -S -H /S /D" + caminho + "\\*.*";

I think that should be it:

        comando_01 = "attrib -R -A -S -H /S /D " + caminho + "\\*.*";

Observe the space after the /D.

And then there’s this:

        executar[0] = cmd + " " + caminho;

Should be:

        executar[0] = cmd + " " + comando_01;

Browser other questions tagged

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