Execute PROMPT / CMD commands in Java [duplicate]

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 for cleaning pendrive viruses. I already consulted some materials here in the forum, but could not apply.

Basically the user will type the letter of his pendrive and click on the execute button, where he 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...");
        }
    
asked by anonymous 27.11.2016 / 05:04

2 answers

2

I think this is wrong here:

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

I think it should be this:

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

Note the space after /D .

And then there's this:

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

Should be:

        executar[0] = cmd + " " + comando_01;
    
27.11.2016 / 05:44
2

You are not changing the drive letter you are trying to access. First place 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 cmd path. It's also important to note that you should get the drive letter you want.

    
27.11.2016 / 05:43