0

stream close while 2nd object call to getMatrix() method for input data #

** I am trying to read data from keyboard using BufferedReader obj. for two matrix, using two separate object, when use 1st object work properly input but while call trough second object exception raised "STREAM CLOSED" WHY? every object call to getMatrix() method for add data to matrix and data input from keyboard in this method obtain Stream object for get data from keyboard and end of the method close the stream, again call from another object to getMatrix() method and same process but during second object call exception raised...Stream Closed...... **

        package myarray; 
        import java.io.BufferedReader;
        import java.io.IOException;
        import java.io.InputStreamReader;
        import java.util.StringTokenizer;

        public class Matrix
        {
            int r,c;
            int arr[][];//instance optional initialization
            public Matrix(int r, int c) 
            {
                super();
                this.r = r;
                this.c = c;
                arr=new int[r][c];
            }
            //Stream closed problem
            protected int[][] getMatrix() throws IOException
            {
            try(BufferedReader br=new BufferedReader(new InputStreamReader(System.in));)
                {
                StringTokenizer st;
                for(int i=0; i<arr.length; i++)
                    {
                    System.out.println("Enter "+arr[i].length+" Integer separated with space");
                    String s=br.readLine();
                    st=new StringTokenizer(s);
                    for(int j=0; j<st.countTokens(); j++)
                        {
                        arr[i][j]=Integer.parseInt(st.nextToken());
                        }
                    }
                return arr;
                }
            }
            //stream end
            protected int [][]findSum(int a[][],int b[][])
            {
                int temp[][]=new int[r][c];//local must be initialize

                for(int i=0; i<a.length; i++)//outer loop
                    for(int j=0; j<a[i].length; j++)//inner loop
                        temp[i][j]=a[i][j]+b[i][j];//inner loop business logic

                return temp;
            }

            //Display the result matrix
            protected void display(int res[][])
            {
                for(int i=0; i<res.length; i++)
                {
                    for(int j=0; j<res[i].length; j++)
                    {
                        System.out.print(res[i][j]+"  ");
                    }
                    System.out.println();
                }
            }

            public static void main(String[] args) throws IOException 
            {
                Matrix m1=new Matrix(3, 3);//3row and 3 column
                Matrix m2=new Matrix(3, 3);

                System.out.println("Enter element for First matrix");
                int x[][]=m1.getMatrix();

                System.out.println("Enter element for Second matrix");
                int y[][]=m2.getMatrix();

                //add matrix and return result a matrix
                int z[][]=m1.findSum(x, y);

                System.out.println("\nThe Sum Matrix is :");
                m2.display(z);

            }
        }
        /* ******OUTPUT******
        Enter element for First matrix
        Enter 3 Integer separated with space
        1 2 3
        Enter 3 Integer separated with space
        4 5 6
        Enter 3 Integer separated with space
        7 8 9
        Enter element for Second matrix
        Exception in thread "main" Enter 3 Integer separated with space
        java.io.IOException: Stream closed
         * */
Dev
  • 1
  • 2

2 Answers2

0

The problem is that you are creating a BufferedReader using the try-with-resources syntax which closes the resource after use. This syntax is fine for reading data from a file but not from System.in because it not only closes the BufferedReader but also System.in.

Solution:

Create the BufferedReader instance without try-with-resources syntax and DO NOT close it.

Do it as follows:

protected int[][] getMatrix() throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st;
    for (int i = 0; i < arr.length; i++) {
        System.out.println("Enter " + arr[i].length + " Integer separated with space");
        String s = br.readLine();
        st = new StringTokenizer(s);
        for (int j = 0; j < st.countTokens(); j++) {
            arr[i][j] = Integer.parseInt(st.nextToken());
        }
    }
    return arr;
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Yes Arvind Sir! If I does not close Stream then work fine – Dev Apr 27 '20 at 15:48
  • i know but it is possible when i call to without try resources.but want to use try with resources and close stream every time, then what problem – Dev Apr 27 '20 at 15:49
  • @Dev - If you close `System.in`, you have no way to open it again. – Arvind Kumar Avinash Apr 27 '20 at 15:59
  • sir i am already done same code, and work fine ,i want to know "Why not close stream every time" and if i does not close stream then after second object complete my stream is open.. – Dev Apr 27 '20 at 16:01
  • @Dev - I suggest you go through https://stackoverflow.com/questions/27286690/in-java-is-it-possible-to-re-open-system-in-after-closing-it – Arvind Kumar Avinash Apr 27 '20 at 16:02
0

I think the problem is come from:

try(BufferedReader br=new BufferedReader(new InputStreamReader(System.in));)

This syntax called try-with-resources, which will convert to try...finally block at compile time, and after convert, the object inside this block will call close() method (Note that the object itself have to implements AutoCloseable interface to use this feature). This is why the first time you calling the method it fine, but after that, it will close the BufferedReader then therefore the error is saying "STREAM CLOSED"

Hưng Chu
  • 1,027
  • 5
  • 11
  • if i use without try resources then same problem through same exception – Dev Apr 27 '20 at 15:53
  • Following the documentation in System.java file: /** * The "standard" input stream. This stream is already * open and ready to supply input data. Typically this stream * corresponds to keyboard input or another input source specified by * the host environment or user. */ public final static InputStream in = null; Once you close this, you will not be able to open it again – Hưng Chu Apr 27 '20 at 15:54
  • if i use without try with resources and NOT CLOSE close() method then work fine,but i want to close the stream – Dev Apr 27 '20 at 15:55
  • The stream (input / output stream) cannot be open or reproduce again once it has been closed. This input stream corresponds to keyboard input, therefore if you close it, you will not be able to input from the keyboard to your program again until the program shutdown. – Hưng Chu Apr 27 '20 at 15:57