Search code examples
javajoptionpaneprocessbuilderstring-lengthends-with

Java: showInputDialog and ProcessBuilder


I just started coding in Java and i'm trying to make a program to run chkdsk when i click on a JButton. I will put a bit of the code here so you guys can help me:

String disk = JOptionPane.showInputDialog(Janela, "Especifique a letra do disco (Exemplo: C:)", "CHKDSK /F", JOptionPane.QUESTION_MESSAGE);
        if (disk.length() == 2 && disk.endsWith(":")) {
              try {
               String disk2 = ("fsutil dirty set " + disk)
               ProcessBuilder chkdskf = new ProcessBuilder("cmd.exe", "/C", "start", disk2);
               Process chkdskff = chkdskf.start();
              }
              catch (IOException fnfex2) {
               System.out.println ("Erro no CHKDSK /F");
             } 
            }

        else {
            JOptionPane.showMessageDialog(Janela, "Erro!", "Erro", JOptionPane.ERROR_MESSAGE);        
        }

So, it shows a InputDialog so you can put a drive letter (like C: or D:), and after that it checks if the string is the way i want. (Has two characters and ends with a ":"). Then, it starts a new cmd window with the command to make chkdsk run on the next reboot. However, it doesn't work. The CMD window that is opened when the code is executed has the title of "fsutil dirty set C:", but nothing happens, no command is executed. Any help is appreciated, and sorry for my poor english.


Solution

  • From the command line help for start

    STATE ["title"] [/D path] ... [command/program] [parameters]

    So, based on that, it would mean that start is taking fsutil dirty set C: as the title - the reason is because of the way the parameters work in ProcessBuilder.

    Each element in the array is a separate argument been sent to the command, this is really helpful as it means you don't need to worry about quotes or other escaping requirements

    So, based on all of this, you should construct your ProcessBuilder more like...

    ProcessBuilder chkdskf = new ProcessBuilder("cmd.exe", "/C", "start", "Make it so", "fsutil", "dirty", "set", disk);