简体   繁体   中英

IF Condition is Met but skipped to the next IF

I'm not sure why, but while I am trying to debug, I find this is very weird:

在此处输入图片说明

As you see in the image, the value of in.readLine() is null and in.readLine() == null is true . But why it skips the if (in.readLine() == null) { ... line? But when I tried to place the breakpoint in line 266 and 267 , it's entering the code on that condition.

在此处输入图片说明

The code:

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

When your debugger evaluates in.readLine() , it consumes from the reader. Therefore, if you were on the last line of whatever is being read, in.readLine() would be non-null, putting control in the else , but when you evaluate in.readLine() to display in the debugger, it reads again , finds that there are no more lines, and returns null as the value to show in the debugger.

To see the real picture, assign in.readLine() to a variable first, and watch the value of that variable, which won't change by simply reading it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM