java - IF 条件满足但跳到下一个 IF

标签 java if-statement

我不确定为什么,但是在尝试调试时,我发现这很奇怪:

enter image description here

如图所示,in.readLine() 的值为 null 并且 in.readLine() == nulltrue。但为什么它会跳过 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();
        }
    }
}

最佳答案

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

要查看真实图片,请先将 in.readLine() 赋给一个变量,然后观察该变量的值,仅通过读取它不会改变。

关于java - IF 条件满足但跳到下一个 IF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17182439/

相关文章:

javascript - 检查数组中是否存在值

java - 缓存 JNDI 查找

java - org.xml.sax.SAXParseException : Content is not allowed in prolog

java - JPanel观察者

Razor 计数项目

python - 在文本 python 中搜索特定单词

python - 将一个值引用到列表时,是否可以在 python 中快速检查一个值是否等于另一个值?

PHP Mysql - 将数据库 ID 中的所有值加 1,下一个值减去 1

java - Servlet编译错误

java - 为什么对象的声明类型在运行时很重要?