Search code examples
javaprocessexebufferedreaderprocessbuilder

java.io.IOexception when initializing a process


When I compile this code, I get a java.io.IOexception error when initializing process p. However, if I were to put it in a try catch block, I would get an error saying that this varible can't be found, when I try to use it on the line below. Is there a way around the try catch block?

I am trying to run an executable file, that takes a par file as a parameter, and save the output of that executable file to a txt file.

import java.io.*;
import java.util.*;

public class Class{
public static void main (String[] args)
 {

 ProcessBuilder pb = new ProcessBuilder("C:\\....\\c.exe",    "C:\\.....\\w.par");

Process p = pb.start();

BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

Solution

  • If you try to initialize a variable in a try-catch block it will not be "found" outside the scope of the try-catch block. Modify to look like this:

     import java.io.*;
     import java.util.*;
    
     public class Class{
    
         public static void main (String[] args) {
         ProcessBuilder pb = null;
         Process p = null;
    
         try {
         ProcessBuilder pb = new ProcessBuilder("C:\\....\\c.exe", "C:\\.....\\w.par");
    
         Process p = pb.start();
    
         BufferedReader stdInput = new BufferedReader(newInputStreamReader(p.getInputStream()));
         } catch (IOException | ProcessException e) {
             System.err.println("Some error message"); 
         }