Search code examples
javainputstreamdatainputstreambufferedinputstream

issue while extending InputStream class


I am trying to extend InputStream class and use customized read() methods. This is my class snapshot:

class MyClass
{    
     /** Input stream */
     private final MyInputStream in = new MyInputStream();
     /**get the InputStream
     public InputStream getInputStream()
     {
         return in;
     }

     /** Inner class for MyInputStream */
     class MyInputStream extends InputStream
     {
         //here i am keeping implementation of read methods
         public synchronized int read( byte b[] ) throws IOException
         {
         //..................
         }
     }
 }

Here is my client class

public class MyClient {
     //InStreams
     protected BufferedInputStream mBufInStream;
     protected DataInputStream mInStream;

     public int read(byte[] buffer)
     {
           MyClass obj1 =  new MyClass();
           mBufInStream = new BufferedInputStream(obj1.getInputStream());
           mInStream = new DataInputStream(mBufInStream);
           try
           {
               int i = mBufInStream.read(buffer);
               return i;
           }
           catch (IOException ex)
           {
               return -1;
           }
     }

     public static void main(String args[])
     {
        MyClient cl1 = new MyClient();
        int ret = 0;
        byte[] data = {};

        ret = cl1.read(data);

     } 
 }

What i wanted to do is call my read method of MyInputStream Class when cl1.read is done.

I don't know what i am missing here.


Solution

  • I created the DataInputStream object using MyInputStream and got it working. Here is the updated code:

    public class MyClient {
     //InStreams
     protected DataInputStream mInStream;
    
     public int read(byte[] buffer)
     {
           MyClass obj1 =  new MyClass();
           mInStream = new DataInputStream(obj1.getInputStream());
           try
           {
               int i = mInStream.read(buffer);
               return i;
           }
           catch (IOException ex)
           {
               return -1;
           }
     }
    
     public static void main(String args[])
     {
        MyClient cl1 = new MyClient();
        int ret = 0;
        byte[] data = {};
    
        ret = cl1.read(data);
    
     } 
    }