无法从Java程序运行UNIX命令 [英] Unable to run UNIX command from Java program
问题描述
我正在尝试创建一个java程序,它接受一些用户输入变量并将它们传递给perl脚本(它实际上在perl脚本中找到某个字符串并用用户输入变量替换它)。以下是代码:
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);
我正在使用IDE,当sed命令打印到控制台时,它看起来是正确的。我从控制台复制了sed命令并从终端运行它,它工作正常。我编写了字符串testRun以查看Java中的Process是否存在问题,并创建了文件hello.txt。出于某种原因,我的程序没有创建输出perl文件myNEWperlscript.pl。我很困惑为什么这不起作用。任何人都可以帮忙吗?
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()接受带有程序名称和参数的String [],但是你将所有内容连接成一个String,从而有效地丢失了参数。
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.
尝试这样的事情:
String[] cmd = {"sed", "first argument", "second argument"};
Runtime.getRuntime().exec(cmd);
这篇关于无法从Java程序运行UNIX命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!