[英]execute a command using java and save generated output in another directory
I am working on an eclipse rcp product where I need to run a command from one directory and need to save the output in another directory. 我正在开发eclipse rcp产品,需要从一个目录运行命令,并将输出保存到另一个目录。
The output of a command is a file. 命令的输出是一个文件。
I am not getting how to do that. 我没有怎么做。
My code is like this which is not working. 我的代码是这样的,不起作用。
Runtime r = Runtime.getRuntime();
Process p = r.exec(("CMD /C cd D:\\dir1\\bin" + " && " + command),
null, new File("D:\\Data\\test"));
so, command needs to run from dir1/bin and the output of this command is a file which should save in data/test. 因此,命令需要从dir1 / bin运行,该命令的输出是一个文件,应保存在data / test中。
But from the above code, the output(ie. generated file) is saved in dir1/bin which is not expected. 但是从上面的代码中,输出(即生成的文件)保存在dir1 / bin中,这是不期望的。
echo This is a command > output.txt
尝试在命令末尾添加“ > output.txt ”,以将其插入文件
You can use the InputStream given by the process object (p.getInputStream()) and a FileOutputStream to a file. 您可以使用流程对象(p.getInputStream())给定的InputStream和文件的FileOutputStream。 Create a new Thread with an endless while-loop, read the characters within that and write them to the file.
创建一个具有无限while循环的新线程,读取其中的字符并将其写入文件。
Process p = ....
InputStream is = p.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("output.txt"));
new Thread(new Runnable() {
public void run() {
while (true) {
char c = (char)is.read();
if (c > -1) {
fos.write(c);
} else {
return;
}
}
}
}).start();
I did not test the code but it should work. 我没有测试代码,但是应该可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.