IF条件已达到但跳过下一个IF

时间:2013-06-19 03:32:21

标签: java if-statement

我不知道为什么,但在我尝试调试时,我觉得这很奇怪:

enter image description here

正如您在图片中看到的那样,in.readLine()的值为nullin.readLine() == null的值为true。但为什么它会跳过if (in.readLine() == null) { ...行呢?但是,当我尝试将断点放在行266267中时,它会在该条件下输入代码。

enter image description here

代码:

private void startSOfficeService() throws InterruptedException, IOException {
    if (System.getProperty("os.name").matches(("(?i).*Windows.*"))) {
        try {
            //Check if the soffice process is running
            Process process = Runtime.getRuntime().exec("tasklist /FI \"IMAGENAME eq soffice.exe\"");
            //Need to wait for this command to execute
            int code = process.waitFor();

            //If we get anything back from readLine, then we know the process is running
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            if (in.readLine() == null) {
                //Nothing back, then we should execute the process
                String[] SOFFICE_CMD = { SOFFICE_SERVICE_PATH,
                                         "-accept=socket,host=" + SOFFICE_SERVICE_HOST + ",port=" + SOFFICE_SERVICE_PORT + ";urp;", 
                                         "-invisible",
                                         "-nologo"};
                process = Runtime.getRuntime().exec(SOFFICE_CMD);
                code = process.waitFor();
                System.out.println("soffice script started");
            } else {
                System.out.println("soffice script is already running");
            }

            in.close();
            in = null;
            System.gc();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:6)

当您的调试器评估in.readLine()时,它会从阅读器中消耗掉。因此,如果您在读取的任何内容的最后一行,in.readLine()将为非空,将控制权放在else中,但是当您评估in.readLine()以在调试器中显示时,再次读取,发现没有更多行,并返回null作为调试器中显示的值。

要查看实际图片,请先将in.readLine()指定给变量,然后观看该变量的值,只需阅读该变量就不会发生变化。