sed命令不能从java工作 [英] sed command not working from java
问题描述
我试图从java运行 sed
命令但没有成功。这是我的java代码:
I am trying to run a sed
command from java without success. Here is my java code:
String[] cmd = {"sed", "-i", "'"+lineIndex+"s/"+line+"/"+currentBid+"/g'", "/data/jsp/items.xml"};
Runtime.getRuntime().exec(cmd);
我也试过:
String[] cmd = {"/bin/sh","-c","sed", "-i", "'"+lineIndex+"s/"+line+"/"+currentBid+"/g'", "/data/jsp/items.xml"};
Runtime.getRuntime().exec(cmd);
事情是,如果我打印出 cmd String的内容
并在它确实有效的终端中运行它。它只是因为某种原因没有从java执行它。更清楚,当我直接从终端运行命令时,文件items.xml发生了变化。当我从java运行它时,文件不会改变。我已经确认该命令是正确的,如下所示。
Thing is, if I print out the contents of the cmd String
and run it in a terminal it does work. It's just not executing it from java for some reason. Te make this more clear, when I run the command directly from a terminal the file "items.xml" changes. When I run it from java the file does not change. I've verified that the command is correct as sown below.
我错过了什么?
输出来自cmd sed -i'21s / 2/102 / g'/data/jsp/items.xml
**编辑
我根据以下评论做了以下更改。但是输出没有变化。
I made the following changes based on comments below. No change in output however.
String[] cmd = {"/bin/sh","-c","sed", "-i", "'"+lineIndex+"s/"+line+"/"+currentBid+"/g'", "/data/jsp/items.xml"};
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line2 = reader.readLine();
while (line2 != null) {
line2 = reader.readLine();
}
reader.close();
推荐答案
试试:)
这个解决方案的优点是,因为你有临时文件所以更容易调试!
The advantage of this solution , it's more easier to debugging because you have the temporary file !
String lineIndex="21";
String line="2";
String currentBid="102";
File temp = File.createTempFile("temp-sh", ".sh");
FileWriter fw = new FileWriter(temp);
fw.write("#!/bin/bash\n");
fw.write("sed -i '"+lineIndex+"s/"+line+"/"+currentBid+"/g' data/jsp/items.xml\n");
fw.close();
System.out.println(". "+temp.getAbsolutePath());
Runtime.getRuntime().exec(". "+temp.getAbsolutePath());
这篇关于sed命令不能从java工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!