如何在 Java 中运行 Linux 命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3403226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run Linux commands in Java?
提问by chitresh
I want to create diff of two files. I tried searching for code in Java that does it, but didnt find any simple code/ utility code for this. Hence, I thought if I can somehow run linux diff/sdiff command from my java code and make it return a file that stores the diff then it would be great.
我想创建两个文件的差异。我尝试在 Java 中搜索执行此操作的代码,但没有找到任何简单的代码/实用程序代码。因此,我想如果我能以某种方式从我的 java 代码运行 linux diff/sdiff 命令并让它返回一个存储差异的文件,那就太好了。
Suppose there are two files fileA and fileB. I should be able to store their diff in a file called fileDiff through my java code. Then fetching data from fileDiff would be no big deal.
假设有两个文件fileA 和fileB。我应该能够通过我的 java 代码将它们的差异存储在一个名为 fileDiff 的文件中。然后从 fileDiff 获取数据没什么大不了的。
回答by codaddict
You need not store the diff in a 3rd file and then read from in. Instead you make use of the Runtime.exec
您不需要将差异存储在第三个文件中,然后从文件中读取。相反,您可以使用 Runtime.exec
Process p = Runtime.getRuntime().exec("diff fileA fileB");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
回答by paxdiablo
You can use java.lang.Runtime.exec
to run simple code. This gives you back a Process
and you can read its standard output directly without having to temporarily store the output on disk.
您可以使用java.lang.Runtime.exec
来运行简单的代码。这会给你一个Process
,你可以直接读取它的标准输出,而不必将输出临时存储在磁盘上。
For example, here's a complete program that will showcase how to do it:
例如,这是一个完整的程序,它将展示如何做到这一点:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class testprog {
public static void main(String args[]) {
String s;
Process p;
try {
p = Runtime.getRuntime().exec("ls -aF");
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) {}
}
}
When compiled and run, it outputs:
编译并运行时,它输出:
line: ./
line: ../
line: .classpath*
line: .project*
line: bin/
line: src/
exit: 0
as expected.
正如预期的那样。
You can also get the the error streamfor the process standard error, and output streamfor the process standard input, confusingly enough. In this context, the input and output are reversed since it's input fromthe process to this one (i.e., the standard outputof the process).
您还可以获取流程标准错误的错误流,以及流程标准输入的输出流,这很令人困惑。在这种情况下,输入和输出是相反的,因为它是从流程输入到这个流程的(即流程的标准输出)。
If you want to merge the process standard output and error from Java (as opposed to using 2>&1
in the actual command), you should look into ProcessBuilder
.
如果您想合并来自 Java 的流程标准输出和错误(而不是2>&1
在实际命令中使用),您应该查看ProcessBuilder
.
回答by YoK
Runtime run = Runtime.getRuntime();
//The best possible I found is to construct a command which you want to execute
//as a string and use that in exec. If the batch file takes command line arguments
//the command can be constructed a array of strings and pass the array as input to
//the exec method. The command can also be passed externally as input to the method.
Process p = null;
String cmd = "ls";
try {
p = run.exec(cmd);
p.getErrorStream();
p.waitFor();
}
catch (IOException e) {
e.printStackTrace();
System.out.println("ERROR.RUNNING.CMD");
}finally{
p.destroy();
}
回答by Naveen
You can also write a shell script file and invoke that file from the java code. as shown below
您还可以编写一个 shell 脚本文件并从 java 代码调用该文件。如下所示
{
Process proc = Runtime.getRuntime().exec("./your_script.sh");
proc.waitFor();
}
Write the linux commands in the script file, once the execution is over you can read the diff file in Java.
在脚本文件中写入 linux 命令,一旦执行结束,您就可以读取 Java 中的 diff 文件。
The advantage with this approach is you can change the commands with out changing java code.
这种方法的优点是您可以在不更改 java 代码的情况下更改命令。
回答by b10n1k
try to use unix4j. it s about a library in java to run linux command. for instance if you got a command like: cat test.txt | grep "Tuesday" | sed "s/kilogram/kg/g" | sort in this program will become: Unix4j.cat("test.txt").grep("Tuesday").sed("s/kilogram/kg/g").sort();
尝试使用unix4j。它是关于 java 中的一个库来运行 linux 命令。例如,如果你有这样的命令: cat test.txt | grep "星期二" | sed "s/kg/kg/g" | 在这个程序中排序会变成:Unix4j.cat("test.txt").grep("Tuesday").sed("s/kg/kg/g").sort();
回答by nugrahaTeten
if the opening in windows
如果在窗口中打开
try {
//chm file address
String chmFile = System.getProperty("user.dir") + "/chm/sample.chm";
Desktop.getDesktop().open(new File(chmFile));
} catch (IOException ex) {
Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
{
JOptionPane.showMessageDialog(null, "Terjadi Kesalahan", "Error", JOptionPane.WARNING_MESSAGE);
}
}
回答by Sarat Chandra
You can call run-time commands from java for both Windowsand Linux.
您可以从 java 为Windows和Linux调用运行时命令。
import java.io.*;
public class Test{
public static void main(String[] args)
{
try
{
Process process = Runtime.getRuntime().exec("pwd"); // for Linux
//Process process = Runtime.getRuntime().exec("cmd /c dir"); //for Windows
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line=reader.readLine())!=null)
{
System.out.println(line);
}
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
process.destroy();
}
}
}
Hope it Helps.. :)
希望能帮助到你.. :)
回答by Martin
The suggested solutions could be optimized using commons.io, handling the error stream, and using Exceptions. I would suggest to wrap like this for use in Java 8 or later:
建议的解决方案可以使用 commons.io、处理错误流和使用 Exceptions 进行优化。我建议像这样包装以便在 Java 8 或更高版本中使用:
public static List<String> execute(final String command) throws ExecutionFailedException, InterruptedException, IOException {
try {
return execute(command, 0, null, false);
} catch (ExecutionTimeoutException e) { return null; } /* Impossible case! */
}
public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
return execute(command, 0, null, true);
}
public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit, boolean destroyOnTimeout) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
Process process = new ProcessBuilder().command("bash", "-c", command).start();
if(timeUnit != null) {
if(process.waitFor(timeout, timeUnit)) {
if(process.exitValue() == 0) {
return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
} else {
throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
}
} else {
if(destroyOnTimeout) process.destroy();
throw new ExecutionTimeoutException("Execution timed out: " + command);
}
} else {
if(process.waitFor() == 0) {
return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
} else {
throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
}
}
}
public static class ExecutionFailedException extends Exception {
private static final long serialVersionUID = 1951044996696304510L;
private final int exitCode;
private final List<String> errorOutput;
public ExecutionFailedException(final String message, final int exitCode, final List<String> errorOutput) {
super(message);
this.exitCode = exitCode;
this.errorOutput = errorOutput;
}
public int getExitCode() {
return this.exitCode;
}
public List<String> getErrorOutput() {
return this.errorOutput;
}
}
public static class ExecutionTimeoutException extends Exception {
private static final long serialVersionUID = 4428595769718054862L;
public ExecutionTimeoutException(final String message) {
super(message);
}
}
回答by Kailas Kakade
Java Function to bring Linux Command Result!
Java Function 带来 Linux 命令结果!
public String RunLinuxCommand(String cmd) throws IOException {
String linuxCommandResult = "";
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
try {
while ((linuxCommandResult = stdInput.readLine()) != null) {
return linuxCommandResult;
}
while ((linuxCommandResult = stdError.readLine()) != null) {
return "";
}
} catch (Exception e) {
return "";
}
return linuxCommandResult;
}