Search code examples
javahttpspring-mvcjava-iostringbuffer

Index out of bound exception with inputstream data


I was trying to flush data in a file in my local machine to response. But at some point I get an IndexOutOfBoundsException.

FileInputStream inputStream = new FileInputStream(downloadFile);
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer, 0, 4096)) != -1) {
    outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();

The above code is what I was trying. The downloadFile path given is correct and it works till the while loop. But then the IndexOutOfBoundsException occurs. I tried it with inputStream.read(buffer) but that didn't work.


Solution

  • Give code is working perfectlly; since there is no information is given regarding the response object I have modify the OutputStream to FileOutputStream; just to test.

    Below code segment is working perfectly.

    public class Test
    {
        public static void main(String args[]) throws IOException
        {
            FileInputStream inputStream = new FileInputStream("C:\\readme.txt");
            FileOutputStream outputStream = new FileOutputStream("D:\\readme1.txt");
            //OutputStream outStream = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(buffer, 0, 4096)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            inputStream.close();
            outputStream.close();
        }
    }