[英]Exit(1) when running exec on java
当我在 linux 中执行我的 java 文件时,我正在 java 程序中运行 sed 命令。 当我在 linux 中单独运行命令时,这将起作用 -> sed '1d;$d' /home/sample/testdata.txt > /home/output/testupdate.txt
但是,当我在 linux 中运行我的 java 程序时,它返回 exit(1) 错误。 我已经通读并用作数组,但它仍然失败。
public static void main(String[] args) {
String[] cmd = {"sed", "sed '1d;$d' /home/sample/testdata.txt > /home/output/testupdate.txt"};
String s;
Process p;
try {
p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((s = br.readLine()) != null) {
System.out.println("line: " + s);
}
p.waitFor();
System.out.println("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {
}
}
Java 不是 shell,因此不处理重定向 - 您的原始命令只能通过理解“>”的 Linux shell 工作。
你可以让 Java 启动 shell 来执行命令,比如你正在使用 bash:
String[] cmd = {"/bin/bash", "-c"
, "sed '1d;$d' /home/sample/testdata.txt > /home/output/testupdate.txt"};
或者,请参阅其他有用的评论,这些评论链接到其他页面,以处理 Java 代码中的重定向,或者在 Java 本身内部进行(例如使用Files.lines
/streams)。
你不需要sed
。 Java 可以做sed
可以做的一切。
在您的情况下,您似乎正在使用sed
从文件中删除第一行和最后一行。 以下是您在 Java 中的做法:
Path source = Path.of("/home/sample/testdata.txt");
Path destination = Path.of("/home/output/testupdate.txt");
long lineCount;
try (Stream<?> lines = Files.lines(source)) {
lineCount = lines.count();
}
long lastLine = lineCount - 1;
try (BufferedReader in = Files.newBufferedReader(source);
BufferedReader out = Files.newBufferedWriter(destination)) {
// Skip first line
String line = in.readLine();
long counter = 0;
while ((line = in.readLine()) != null) {
if (++counter < lastLine) {
out.write(line);
out.newLine();
}
}
}
如果由于某种原因您绝对需要使用外部进程,那么还有许多其他问题和答案可以涵盖您的错误: >
sed
无法理解。 通常,解释文件重定向的是 shell(如bash
)。
运行命令的正确方法是:
ProcessBuilder builder =
new ProcessBuilder("sed", "1d;$d", "/home/sample/testdata.txt");
builder.redirectOutput(new File("/home/output/testupdate.txt"));
builder.redirectError(ProcessBuilder.Redirect.INHERIT);
Process p = builder.start();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.