如何从Java程序在Linux中打开另一个命令行应用程序?

时间:2021-04-01 20:49:32

I'm trying to write a small Java command-line application that will create a new file, and then open it with the systems default editor stored in $EDITOR, and then exit after the editor is closed.

我正在尝试编写一个小的Java命令行应用程序,它将创建一个新文件,然后使用存储在$ EDITOR中的系统默认编辑器打开它,然后在编辑器关闭后退出。

So far, without luck, I've tried the following:

到目前为止,没有运气,我尝试了以下内容:

Desktop dt = Desktop.getDesktop();
dt.edit(file);

This method resulted in an UnsupportedOperationException, which sort of makes sense as I'm running my program from the terminal, not as a Java appliacation from the desktop.

这种方法导致了UnsupportedOperationException,当我从终端运行我的程序时,这种方式有意义,而不是桌面上的Java应用程序。

Right now, I have this:

现在,我有这个:

Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(commandString); // "vim newfile"
proc.waitFor();

This is working, but not how I need it to. When I run

这是有效的,但不是我需要它。当我跑

ps a | grep vim

I can see that it is indeed running in the background, with the filename I've given it:

我可以看到它确实在后台运行,我给它的文件名:

1000 pts/1    S+     0:00 vim 2014-07-16.23-02

Any ideas on how to make this run in the foreground?

关于如何让它在前台运行的任何想法?

1 个解决方案

#1


1  

vim, like many interactive programs, expects its stdin to be a real terminal that it can send ioctl calls to. But when executing through Runtime.exec() stdin will be redirected to the parent process (see the Javadoc on Process for more information).

像许多交互式程序一样,vim期望它的stdin是一个可以发送ioctl调用的真正终端。但是当通过Runtime.exec()执行时,stdin将被重定向到父进程(有关更多信息,请参阅进程上的Javadoc)。

In Java 7, you should be able to use ProcessBuilder.inheritIO() to pass along the file handles. (Disclaimer: I haven't tried it, YMMV.)

在Java 7中,您应该能够使用ProcessBuilder.inheritIO()传递文件句柄。 (免责声明:我没试过,YMMV。)

#1


1  

vim, like many interactive programs, expects its stdin to be a real terminal that it can send ioctl calls to. But when executing through Runtime.exec() stdin will be redirected to the parent process (see the Javadoc on Process for more information).

像许多交互式程序一样,vim期望它的stdin是一个可以发送ioctl调用的真正终端。但是当通过Runtime.exec()执行时,stdin将被重定向到父进程(有关更多信息,请参阅进程上的Javadoc)。

In Java 7, you should be able to use ProcessBuilder.inheritIO() to pass along the file handles. (Disclaimer: I haven't tried it, YMMV.)

在Java 7中,您应该能够使用ProcessBuilder.inheritIO()传递文件句柄。 (免责声明:我没试过,YMMV。)