I need to copy into one file half of all bytes, into the second file the second half (or most if the number of bytes is not equal).

int size = fileInputStream.available(); int middle; if(size%2==0) middle = size/2; else middle = (size-1)/2 ; byte b[] = new byte[size]; while (fileInputStream.available()>0) { fileInputStream.read(b); fileOutputStream.write(b, 0, middle ); fileOutputStream2.write(b, middle, b.length); } /***в этом месте вылазит эксцепшин IndexOutOfBoundsException, возможно я не правильно себе представляю то как работают методы, мне казалось что я первую половину байтов писал в первый файл, а вторую половину во второй файл,почему у меня не верно, и как правильно?***/ } 

I incorrectly apparently imagine the write method. The way I imagine my code inside while (everything that is above me doesn’t really matter, I just wrote that there were fewer questions about what kind of variables) First I write to the byte array, all the content. then I write to the first file write from 0 to the middle of my array. Then I write to the second file from the place where I left it, to the end of the array.? Obviously I am wrong, but I do not understand why ..., how to input, output in two files equally (+ - 1 byte) using exactly arrays of bytes?

  • the last element of the array will be b.length-1 - NetL
  • I tried to write like that, but the error crashes out all the time IndexOutOfBoundsException even if you make a -2, well, -1 too. I do not understand why. - Kirill Kirillov

1 answer 1

In the FileOutputStream.write() method, the last parameter is the number of bytes, and not the index of the last byte, as you expect. Hence the exception.

  • you clarified, thanks. - Kirill Kirillov