Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Reading inputstream into a byte array

807603Nov 1 2007 — edited Nov 1 2007
Hi,

I wrote the following code and trying to read in the InputStream and save to a byte array.
    static byte[] getBytes(ServletInputStream inputStream, int lengthOfBuffer) throws Exception {
        
        byte[] data = new byte[lengthOfBuffer];
        BufferedInputStream bufferedInputStream = new BufferedInputStream((InputStream)inputStream, lengthOfBuffer );
        int offset = 0;
        int readBytes = -1;
        while((readBytes = bufferedInputStream.read(data, offset, lengthOfBuffer-offset)) != -1) {
          offset+=readBytes;
        }
        //close the input stream and return data
        bufferedInputStream.close();
        return data;
    }     
Would you please confirm if this code does what I had intended to do. Please note that I am getting the InputStream as follows in my Servlet class.
...
        try {
            ServletInputStream inputStream = request.getInputStream();
...
Thanks in advance,

Mustafa
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 29 2007
Added on Nov 1 2007
3 comments
205 views