3

I am trying to run a file called test.pdf which is located at C:/Software/ using ProcessBuilder. Following is my code

public static void main(String[] args) throws IOException {

         ProcessBuilder pb = new ProcessBuilder("test.pdf");
         pb.directory(new File("C:/Software/"));
         pb.start();

    }

And I'm getting the following exception.

Exception in thread "main" java.io.IOException: Cannot run program "test.pdf" (in directory "C:\Software"): CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at com.test.Test.main(Test.java:12)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    ... 2 more

I checked this How to set working directory with ProcessBuilder thread in stackoverflow. But didn't have any luck. Can anyone help on this? Thanks

Aragon
  • 143
  • 2
  • 9

1 Answers1

2

Use below code :

        String fileToOpen = "test.pdf";
        List<String> command = new ArrayList<String>();
        command.add("rundll32.exe");
        command.add("url.dll,FileProtocolHandler");
        command.add(fileToOpen);

        ProcessBuilder builder = new ProcessBuilder();
        builder.directory(new File("C://Software//"));
        builder.command(command);

        builder.start();

It will open your pdf .
Just change the file name if you want to open other file in same directory.

dangi13
  • 1,275
  • 1
  • 8
  • 11
  • Thanks for the answer. But my intention is to change the current working directory to other directory so that I can execute some commands from that directory. That's why I used ProcessBuilder. – Aragon Jul 20 '18 at 12:01
  • updated answer fro opening pdf using ProcessBuilder. – dangi13 Jul 20 '18 at 13:14