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

IO.read and System.setIn interaction

XMLWordPrintable

    • generic
    • generic

      ADDITIONAL SYSTEM INFORMATION :
      Does not depend on OS.

      A DESCRIPTION OF THE PROBLEM :
      Since in IO the reader is statically initialized, if System.setIn is called after the first read, it has no effect.

      In some test it's useful to be able to re-set System.in, but if it is then read with IO.read the System.setIn has no effect.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Use the provided code


      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      RUN 0
      Read: Run 0
      Read: hello world
      Read: second line
      RUN 1
      Read: Run 1
      Read: hello world
      Read: second line
      RUN 2
      Read: Run 2
      Read: hello world
      Read: second line
      RUN 3
      Read: Run 3
      Read: hello world
      Read: second line
      RUN 4
      Read: Run 4
      Read: hello world
      Read: second line
      RUN 5
      Read: Run 5
      Read: hello world
      Read: second line
      ACTUAL -
      RUN 0
      Read: Run 0
      Read: hello world
      Read: second line
      RUN 1
      RUN 2
      RUN 3
      Read: Run 3
      Read: hello world
      Read: second line
      RUN 4
      Read: Run 4
      Read: hello world
      Read: second line
      RUN 5
      Read: Run 5
      Read: hello world
      Read: second line

      ---------- BEGIN SOURCE ----------
      import java.io.ByteArrayInputStream;
      import java.nio.charset.StandardCharsets;
      import java.util.Scanner;

      public class ReproIO {
        public static void main(String[] args) {
          for (int run = 0; run < 3; run++ ) {
            String simulated = "Run " + run + "\nhello world\nsecond line\n";
            System.out.println("RUN " + run);
            ByteArrayInputStream bais = new ByteArrayInputStream(simulated.getBytes(StandardCharsets.UTF_8));
            System.setIn(bais);
            String line;
            while ((line = IO.readln()) != null)
              IO.println("Read: " + line);
          }
          for (int run = 3; run < 6; run++ ) {
            String simulated = "Run " + run + "\nhello world\nsecond line\n";
            System.out.println("RUN " + run);
            ByteArrayInputStream bais = new ByteArrayInputStream(simulated.getBytes(StandardCharsets.UTF_8));
            System.setIn(bais);
            Scanner s = new Scanner(System.in);
            while (s.hasNextLine())
              IO.println("Read: " + s.nextLine());
          }
        }
      }
      ---------- END SOURCE ----------

            jlahoda Jan Lahoda
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Resolved: