Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8154441

java.util.Scanner hasNext method returns false if 0 bytes read

XMLWordPrintable

    • generic
    • generic

      FULL PRODUCT VERSION :
      $ java -version
      java version "1.8.0_77"
      Java(TM) SE Runtime Environment (build 1.8.0_77-b03)
      Java HotSpot(TM) 64-Bit Server VM (build 25.77-b03, mixed mode)

      ADDITIONAL OS VERSION INFORMATION :
      $ uname -a
      Darwin jfitzpat-mbpr15.xxxxxxxx.com 14.3.0 Darwin Kernel Version 14.3.0: Mon Mar 23 20:23:44 PDT 2015; root:xnu-2782.20.48~8/RELEASE_X86_64 x86_64

      A DESCRIPTION OF THE PROBLEM :
      The java.util.Scanner class can be used to tokenize input for an arbitrary input stream. In some cases a read operation may only read 0 bytes but then later read more than 0 bytes, e.g. if input is coming from the network. On reading 0 bytes, it appears that java.util.Scanner.hasNext() incorrectly returns false whereas I would expect this to occur only in the case where the end of the input stream has been reached.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Put the contents of the following source in a file called "ScannerHasNextBug.java".

      import java.io.IOException;
      import java.io.InputStream;
      import java.util.Scanner;

      public class ScannerHasNextBug {

          public static void main(String[] args) {
              InputStream inputStream = new InputStream() {
                  private boolean firstRead = true;

                  @Override
                  public int read() throws IOException {
                      throw new RuntimeException("Not supported");
                  }

                  @Override
                  public int read(byte[] b, int offset, int length) {
                      if (firstRead) {
                          firstRead = false;
                          return 0;
                      }
                      
                      b[offset] = 'A';
                      
                      return 1;
                  }
              };

              try (Scanner scanner = new Scanner(inputStream)) {
                  System.out.println(scanner.hasNext());
              }
          }
      }

      mkdir classes
      javac -d ./classes ScannerHasNextBug.java
      java -cp ./classes ScannerHasNextBug

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      I expect the output of the above program to be "true".
      ACTUAL -
      The actual output of the above program is "false".

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      See section on "Steps to Reproduce".
      ---------- END SOURCE ----------

            bchristi Brent Christian
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: