使用Runtime.getRuntime()。exec()重定向不起作用 [英] Redirection with Runtime.getRuntime().exec() doesn't work
问题描述
我需要从程序中执行命令。命令行没关系,我在终端试了一下,但它在程序中不起作用。
I need to execute a command from a program. The command line is ok, I tried it in the terminal, but it doesn't work in the program.
我从我的代码中添加了一个副本:
I add a copy from my code:
File dir = new File("videos");
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
System.out.print("No existe el directorio\n");
} else {
for (int i=0; i<children.length; i++) {
// Get filename of file or directory
String filename = children[i];
//Recojo el momento exacto
System.out.print("\n" +filename);
Process p = Runtime.getRuntime().exec("exiftool -a -u -g1 -j videos/"+filename+">metadata/"+filename+".json");
}
程序必须获取文件夹中所有文件的名称(文件名)并提取theese视频的元数据,将它们写在'元数据'文件夹中的.json文件上。
问题出在哪里?
The program must get the name of all of the files in a folder (filename) and extract the metadata of theese videos, writting them on a .json files in the folder 'metadata'.
Where is the problem?
推荐答案
问题是,重定向字符(>
)是一个基于shell的结构,不是可执行文件。因此,除非你通过 bash
(你不是)这样的命令运行这个命令,否则它将被解释为 exiftool
调用。
The problem is, the redirection character (>
) is a shell-based construct, not an executable. So unless you're running this command through something like bash
(which you're not), it's going to be interpreted as a literal character argument to your exiftool
invocation.
如果你想让它工作,你有两个选择:
If you want to get this to work, you have two options:
- 获取bash来执行此操作 - 将整个命令行作为参数传递给
bash -c
。这可能需要一些英勇的转义,虽然在你的情况下看起来没问题。 - 在Java中自己进行重定向。在没有重定向输出的情况下调用命令(即一切都达到
>
符号),然后从进程'outputstream读取并将所有内容写入相应的文件。
- Get bash to do it - pass the whole command line as an argument to
bash -c
. This might need some heroic escaping, although in your case it looks OK. - Do the redirection yourself within Java. Invoke the command without the redirected output (i.e. everything up to the
>
sign), then read from the process' outputstream and write all the contents to the appropriate file.
后一种方法听起来像最初的工作,但当你认为你总是需要总是阅读一个进程的输出(参见 javadocs ,第2段),它实际上是非常少的额外的。您只需将此输出发送到文件而不是将其丢弃。
The latter approach sounds like more work initially, but when you consider that you need to always read a Process' output anyway (see the javadocs, second paragraph), it's actually very little extra on top of that. You're simply sending this output to a file instead of throwing it away.
这篇关于使用Runtime.getRuntime()。exec()重定向不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!