The following is the code I'm studying:
FileInputStream stream = new FileInputStream("/home/rafael/2015.json"); // esse aquivo tem 24 bytes
byte[] result = new byte[(int) stream.getChannel().size()];
int offset = 0;
int read = 0;
while((read = stream.read(result, offset, 8)) != -1){
offset += read;
}
stream.close();
But I've been getting the following exception:
Exception in thread "main" java.lang.IndexOutOfBoundsException
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(FileInputStream.java:272)
at br.com.rafael.socket.Main.main(Main.java:17)
I have already checked my offset, and it works correctly. What can it be?
- adding a debug
FileInputStream stream = new FileInputStream("/home/rafael/2015.json");
byte[] result = new byte[(int) stream.getChannel().size()];
int offset = 0;
int read = 0;
while((read = stream.read(result, offset, 8)) != -1){
offset += read;
System.out.println("read: " + read);
System.out.println("offset: " + offset);
}
System.out.println("o que foi lido? " + new String(result, "UTF-8"));
stream.close();
console:
read: 8
offset: 8
read: 8
offset: 16
read: 8
offset: 24
Exception in thread "main" java.lang.IndexOutOfBoundsException
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(FileInputStream.java:272)
at br.com.rafael.socket.Main.main(Main.java:17)
- adding resolution:
1st decreases read size by 1 byte / iteration
while((read = stream.read(result, offset += read, 1)) != -1){}
2º I increased the result array by 1 index
byte[] result = new byte[stream.available() + 1];
And now it worked perfectly:
BUT I get the last index of my array result
with value 0
- best solution
FileInputStream stream = new FileInputStream("/home/rafael/2015");
byte[] result = new byte[stream.available()];
int offset = 0;
int read = 0;
int buffer = 256;
int remain = result.length;
while((remain -= read = stream.read(result, offset += read, buffer >= remain ? remain : buffer)) > 0){}
stream.close();