问题描述
试图解决这个问题,我几乎死了.有人可以帮忙吗...
I am almost dead trying to sort this out.. Can someone help... please?
下面是代码:
import java.io.*;
import java.lang.Runtime;
import java.util.*;
public class WORKBRO {
public static void main(String args[])
{
try
{
String target = new String("/home/dhirendra.panwar/Desktop/test.sh");
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(target);
} catch (Throwable t)
{
t.printStackTrace();
}
}
}
推荐答案
您的代码正确,并且我确定您没有异常,如果使用proc.getErrorStream()
进行读取,则不会有任何结果.
已经说过,现在命令是100%以这种方式执行,这是因为您正在回显某些内容,您需要使用BufferedReader
读回它.
Your code is right and I am sure you are not getting exceptions, if you read using proc.getErrorStream()
you will not get anything.
Commands 100% get executed that way, having said that now thing is that you are echo'ing something and you need to read it back using BufferedReader
.
检查以下示例,该示例将成功创建一个名为"stackOverflow"的目录并打印您正在回显的内容.恐怕要将其放入日志文件中,恐怕可以使用>"来完成,您可能必须使用一些编辑器命令或使用Java创建文件.
Check below example which will successfully create a directory called "stackOverflow" and print what you are echo'ing. For the putting it into a log file I am afraid that you can do it using ">", you may have to use some editor command or create file using Java.
底线: Runtime.getRuntime().exec("command")
是从Java执行Unix命令或脚本的正确且已定义的方法.
Bottom line: Runtime.getRuntime().exec("command")
is the correct and defined way to execute Unix commands or scripts from Java and it WORKS.
test.sh
#!/bin/bash
echo "hola"
mkdir stackOverflow
Test.java
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
try {
String target = new String("/home/hagrawal/test.sh");
// String target = new String("mkdir stackOver");
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(target);
proc.waitFor();
StringBuffer output = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
System.out.println("### " + output);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
这篇关于从Java代码运行Shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!