尝试Regex匹配Processbuilder输出时出现异常

时间:2013-04-07 14:08:20

标签: java processbuilder

我有以下代码:

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();
    }

由于“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)

为什么我会收到此异常?我想这是因为变量线很忙?

2 个答案:

答案 0 :(得分:6)

line为空时,在循环之后调用此行。

Matcher m = p.matcher(line);

您应该将此行添加到循环中。

答案 1 :(得分:3)

while循环只会在line为空时停止循环。

您无法调用matcher() null。