IllegalArgumentException when executing command with ProcessBuilder in Java -


i'm writing simple java application user can execute cmd commands. there textfield enter command , button execute it. code looks 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 user executes

notepad.exe

but reason java.lang.illegalargumentexception if command example:

"c:\users\username\appdata\local\google\chrome\application\chrome.exe" www.youtube.com

it's because of quotes, know workaround this?

processbuilder expects list of arguments passed list<string> or string.... problem passing 2 separate arguments 1 because have space not in quotes. need split user command on spaces not placed in quotes. can use

pattern p = pattern.compile("\"[^\"]+\"|\\s+"); //pattern find strings between quotes or separate words matcher m = p.matcher(usercmd); while (m.find()) {     system.out.println("adding " + m.group());//just debugging      list.add(m.group()); } 

like in example

string usercmd="\"c:\\users\\username\\appdata\\local\\google\\chrome\\application\\chrome.exe\""         +" www.youtube.com";  list<string> list=new arraylist<>(); list.add("cmd.exe"); list.add("/c");  pattern p = pattern.compile("\"[^\"]+\"|\\s+"); matcher m = p.matcher(usercmd); while (m.find()) {     system.out.println("adding " + m.group());     list.add(m.group()); }  processbuilder pb = new processbuilder(list); process pr = pb.start();  inputstream err=pr.geterrorstream(); bufferedreader errreader=new bufferedreader(new inputstreamreader(err)); string line=null; while((line=errreader.readline())!=null){     system.out.println(line); } 

which in case prints error not finding such path on computer, in user computer should work fine.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -