sed 命令不适用于 Java [英] sed command not working from java

查看:32
本文介绍了sed 命令不适用于 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
");
fw.write("sed -i '"+lineIndex+"s/"+line+"/"+currentBid+"/g' data/jsp/items.xml
");
fw.close();
System.out.println(". "+temp.getAbsolutePath());
Runtime.getRuntime().exec(". "+temp.getAbsolutePath());

这篇关于sed 命令不适用于 Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆