简体   繁体   中英

How can I open another command line application in Linux from a Java program?

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.

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.

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?

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 ).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM