0
follows the excerpt of the code I am 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 checked my offset, and it works correctly. What can 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 remanufacturing:
1º decreases the reading size to 1 byte / iteration
while((read = stream.read(result, offset += read, 1)) != -1){}
2º I increased the result array in 1 index
byte[] result = new byte[stream.available() + 1];
and now it worked perfectly:
HOWEVER i get the last input of my array result
with the 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();
You’re not doing Parsing so java can read the json content. Try debugging your code by placing a breakpoint in while, and you’ll see that it already returns -1, the cause of the exception, because Stream.read is receiving negative Dice.
– user28595
added a debug
– user155542
You don’t understand, reread what I said, so you won’t be able to read json. Look this question in Soen and see, you need an API that does Parsing.
– user28595
no no.. I don’t want to parse yet.. I want to first read the file string.
– user155542
See if the solution to the answer solves the problem.
– user28595
In fact, I just want to really understand the behavior of this method. It’s just a study.
– user155542