我试图sed从Java 运行命令而没有成功。这是我的Java代码:
sed
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运行它时,文件不会更改。我已验证该命令正确无误,如下所示。
cmd String
我想念什么吗?
cmd的输出是 sed -i '21s/2/102/g' /data/jsp/items.xml
sed -i '21s/2/102/g' /data/jsp/items.xml
**编辑
我根据以下评论进行了以下更改。但是输出没有变化。
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();
试试看:)
这种解决方案的优点是,您有了临时文件,调试起来更加容易!
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());