javadirectorycacls

Locking folder with cacls not working


So I've been trying to make an app that would lock a folder. It was working just fine until I added a jtextfield where you could specify the path of the folder and the name of the folder.

This is the array to lock and unlock the folder:

String[] lock = new String[]{"cmd.exe", "/C", "cd \"" + String.valueOf(path.getText())+ "\" && dir", "&", "cacls", String.valueOf(name.getText()), "/e", "/c", "/d", "%username%"};
String[] unlock = new String[]{"cmd.exe", "/C", "cd \"" + String.valueOf(path.getText())+ "\" && dir", "&", "cacls", String.valueOf(name.getText()), "/e", "/c", "/g", "%username%:f"};

And this is the action listener for the two buttons:

block.addActionListener(e -> {
        if (password.getText().toString().equals(passwordText)) {
            try {
                Process p = Runtime.getRuntime().exec(lock);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } else {
            password.setText("");
            passwordLabel.setText("Incorrect password");
            failed.get().start();
        }


    });
unblock.addActionListener(e -> {
        if (password.getText().toString().equals(passwordText)) {
            try {
                Process p = Runtime.getRuntime().exec(unlock);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } else {
            password.setText("");
            passwordLabel.setText("Incorrect password");
            failed.get().start();
        }

    });

When I was specifying directly the path and name it was working fine but now it doesn't do anything. (Sorry for my bad english. Feel free to correct me)


Solution

  • Your error was to initialize the variables lock and unlock before there is a valid value in the JTextFields (at that time, the fields value are empty strings or null). Instead, you should initialize them just before calling Runtime.exec.