I'm writing a simple Java Application where user can execute cmd commands. There is just a TextField to enter the command and a button to execute it. The code looks as follows:
sendButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", message.getText());
Process pr = pb.start();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
Everything works fine if the user executes
notepad.exe
But for some reason I get the java.lang.IllegalArgumentException if the command is for example:
"C:\Users\Username\AppData\Local\Google\Chrome\Application\chrome.exe" www.youtube.com
It's probably because of the quotes, does anybody know a workaround for this?
IllegalArgumentExceptionbasically means Command not found.Process pr = pb.start();execand (continue to) build theProcessusing aProcessBuilder. Also break aString argintoString[] argsto account for arguments which themselves contain spaces.