Search code examples
javaprocessbuilder

Exception when trying to Regex match Processbuilder output


I have the following code:

private void GetInfo(String src) throws IOException{

        Scanner scan = new Scanner(System.in);          
        String filename = new File(src).getName();

        ProcessBuilder builder = new ProcessBuilder("/Users/Daim/Desktop/process", src);
        builder.redirectErrorStream(true);
        Process process = builder.start();
        final InputStream is = process.getInputStream();

            new Thread(new Runnable() {
                String line;
                @Override
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(new InputStreamReader(is));
                        while ((line = br.readLine()) != null) {
                            System.out.println(line);
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    Pattern p = Pattern.compile("least");
                    Matcher m = p.matcher(line);

                    //System.out.println("match");

                }

            }).start();
    }

Getting exception because of "Matcher m = p.matcher(line);":

Exception in thread "Thread-1" java.lang.NullPointerException
    at java.util.regex.Matcher.getTextLength(Matcher.java:1234)
    at java.util.regex.Matcher.reset(Matcher.java:308)
    at java.util.regex.Matcher.<init>(Matcher.java:228)
    at java.util.regex.Pattern.matcher(Pattern.java:1088)
    at Wds$2.run(Wds.java:152)
    at java.lang.Thread.run(Thread.java:722)

Why am I getting this exception? I guess it's because the variable line is busy?


Solution

  • This line is called after the loop, when line is null.

    Matcher m = p.matcher(line);
    

    You should add this line to the loop.