简体   繁体   中英

Unable to run UNIX command from Java program

I am trying to create a java program that takes some user-input variables and passes them to a perl script (it actually finds a certain string within the perl script and replaces it with the user-input variables). Here is the code:

    String sedMain = "sed -e ";
    String sedFirstLine = "'s/AAA/"+newFirstLine+"/' -e ";
    String sedNewCntr = "'s/BBB/"+newCntr+"/' -e ";
    String sedNewSpacing = "'s/SPACE/"+newSpacing+"/' -e ";
    String sedNewDmax = "'s/MAX/"+newDmax+"/'";
    String sedFile = " /filepath/myperlscript.pl >  /filepath/myNEWperlscript.pl";
    String sedCommand=sedMain+sedFirstLine+sedNewCntr+sedNewSpacing+sedNewDmax+sedFile;
    System.out.println("SED COMMAND: "+sedCommand);
    String testRun = "touch /filepath/hello.txt";
    Process runSedCommand;
    runSedCommand = Runtime.getRuntime().exec(sedCommand);

I am using an IDE, and when the sed command is printed to the console, it looks correct. I copied the sed command from the console and ran it from the terminal, and it worked. I wrote the string "testRun" to see if there was a problem with the Process in Java, and it created the file "hello.txt". For some reason though, my program is not creating the output perl file "myNEWperlscript.pl". I am very confused as to why this is not working. Can anyone help out?

exec() takes a String[] with the program name and paramaters as its elements, but you are concatenating everything together into a single String and so effectively loosing the arguments.

Try something like this:

String[] cmd = {"sed", "first argument", "second argument"};
Runtime.getRuntime().exec(cmd);

use the

exec(String[] cmdarray) 

signature. the command is sed, -e is a parameter, 's/AAA/\\n/' is another parameter and so on. So you will have

String[] command = new String[] {"sed", "-e", "s/AAA/\n/", "next parameter without single quotes", , "next parameter without quotes..."}
Runtime.getRuntime.exec(command);

This is the only way your parameters will get well formatted on it's way to the shell, otherwise weird sruff can happen as any quotes after the first token on the string will be considered to be just one parameter and so quotes can be escaped and things like that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM