Search code examples
javaruntimeprocessbuilder

Setting working directory for ProcessBuilder is not working


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


Solution

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