0

My code:

ProcessBuilder builder = new ProcessBuilder();
builder.command("n");

File file = new File("..");
builder.directory( file );

try {
        Process p = builder.start();
} catch (Exception e) {
    System.out.println(e);
} 

Eclipse says:

java.io.IOException
Cannot run program "n" (in directory ".."): CreateProcess error=2, The system cannot find the file specified

But the file n.txt is there, if I say:

for(String fileNames : file.list()) System.out.println(fileNames);

It's listed: n.txt. Same problem if I substitute "n.txt" with "n" in the sourcecode or try to call a .exe;

System.out.println(file.getCanonicalPath());

Creates

F:\Programme\eclipse\workspaces\test

This:

System.out.println(builder.directory().getAbsolutePath());

Creates

F:\Programme\eclipse\workspaces\SimulatorAddOn\SimulatorAddOn\..

And substituting

ProcessBuilder builder = new ProcessBuilder();
builder.command("n");

with

ProcessBuilder builder = new ProcessBuilder("n");

Doesn't change anything either.

I need your help guys. Thanks in advance

Bono
  • 4,757
  • 6
  • 48
  • 77
murkr
  • 634
  • 5
  • 27
  • 1
    Why do you want to run a text file? If you want to open it with the default program, see http://stackoverflow.com/questions/550329/how-to-open-a-file-with-the-default-associated-program – Adrian Leonhard Feb 26 '15 at 17:10
  • like i said, i actually try to run a .exe in the same folder. if I say Desktop.getDesktop().open( file); n.txt opens, but I have to adjust to File file = new File("..\\n.txt"); – murkr Feb 26 '15 at 17:21

1 Answers1

1

I believe the reason why the system cannot find the file is that the directory method only sets the working directory of processes that are run by the builder (from the Javadocs):

Sets this process builder's working directory. Subprocesses subsequently started by this object's start() method will use this as their working directory.

So you need this:

builder.command("..\\n.txt");

for the system to find your file. This still won't do anything useful, you'll get an error similar to:

Cannot run program "..\n.txt" (in directory ".."): CreateProcess error=193, %1 is not a valid Win32 application

The process builder requires a valid appication in your operating system.

Pete
  • 660
  • 6
  • 10
  • builder will look for the file in the current working directory, see http://stackoverflow.com/questions/4871051/getting-the-current-working-directory-in-java for how to get it. – Adrian Leonhard Feb 26 '15 at 17:32
  • 1
    I didn't explain myself very well the first time: I'm actually tring to run an exe. If I use your idea with .command("..\test.exe"); it says now: The requested operation requires elevation – murkr Feb 26 '15 at 17:33
  • @murkr The process you're trying to run cannot due to some security issue, which is a whole other question! Looks like it might be something to do with Windows UAC [see this question](http://stackoverflow.com/q/5853529/1879990) – Pete Feb 26 '15 at 17:54