3

How can I open vi editor from my java application? I have already tried this

Process p = new ProcessBuilder("xterm","-e","vi /backup/xyz/test/abc.txt").start();  

int exitVal = p.waitFor();
System.out.println("Exited with error code "+exitVal);

But this opens vi in a new terminal. I want the vi editor to open in the same terminal that my application is running

Clark
  • 1,357
  • 1
  • 7
  • 18
san2505
  • 51
  • 3

2 Answers2

2

Should be simple: leave out the xterm, just start vi:

Process p = new ProcessBuilder("vi", "/backup/xyz/test/abc.txt").start();  

If you want more command line arguments for vi, add them as separate strings, not inside the "" of first argument.

And launching a terminal program like vi naturally requires, that you started the java app from visible terminal, so vi has a terminal to use, but I assume this is so.

hyde
  • 60,639
  • 21
  • 115
  • 176
  • So if I just use Process p = new ProcessBuilder("vi /backup/xyz/test/abc.txt").start(); It compiles but while running it gives me this error Cannot run program "vi /backup/xyz/test/abc": java.io.IOException: error=2, No such file or directory – san2505 Nov 06 '12 at 19:00
  • @san2505 I made answer more specific – hyde Nov 06 '12 at 19:20
  • @san2505 - you probably have to use a path that actually exists on your machine. I believe that was just an example... – jahroy Nov 06 '12 at 19:23
  • You forgot a comma. A working version would be `p = new ProcessBuilder("vi", "/backup/xyz/test/abc.txt").start();` I suppose. – pvorb Nov 06 '12 at 19:23
  • I m actually using a VM to run this application. Is it the case that I need to specify a proper path for vi command as well? – san2505 Nov 06 '12 at 20:53
  • 1
    But when I run this command, it hangs and do nothing. I think the vi start running in the background. Is there a way to pull it o the same terminal ? – san2505 Nov 06 '12 at 21:53
  • What happens if you press ctrl-C on the terminal so Java program is terminated, and then run vi from command line? – hyde Nov 07 '12 at 06:21
2

The problem was highlighted here:

How can I launch VI from within Java under commons-exec?

However since Java 1.7 you can use the next example to transparently redirect and have full console functionality

    System.out.println("STARTING VI");
     ProcessBuilder processBuilder = new ProcessBuilder("/usr/bin/vi");
     processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
     processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
     processBuilder.redirectInput(ProcessBuilder.Redirect.INHERIT);

     Process p = processBuilder.start();
      // wait for termination.
      p.waitFor();
    System.out.println("Exiting VI");

This will allow you to open VI transparently.

Community
  • 1
  • 1
abr
  • 180
  • 1
  • 3