Question

OK, so I've been trying to read a ("any") binary file to a byte[] array using FileInputReader.read()...But no matter the file length it only reads 5 bytes at a time... (btw im using udp to send the array/file)

byte[] array_bytes = new byte[1024];

while((nread=file.read(array_bytes))!=-1){

            number_bytesread += array_bytes.length;
            socket_udp.send(send_package);

            count += 1;
        }

-send_package is a datagrampacket using array_bytes to send the message

I've tried to use the function read(byte[], offset, lenght), but if I put the lenght over 5, it occurs this error, at the first time reading, even thought the file is surely bigger than 5 bytes:

nread=file.read(array_bytes, 0, 1024);

no need for offset since i send immediatly after reading.

Exception in thread "main" java.lang.IndexOutOfBoundsException
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(FileInputStream.java:272)
at udp_server2.UDP_Server2.Send_Udp(UDP_Server2.java:122)
at udp_server2.UDP_Server2.main(UDP_Server2.java:77)
Java Result: 1

Thanks in advance for the help, André

Était-ce utile?

La solution

It sounds like your array length isn't actually 1024. I know you've shown code creating it with 1024 bytes, but I suspect your actual code either changes the value somewhere else, or that it's created in a different way.

It would be helpful if you could show a short but complete program demonstrating the problem, but failing that, the first diagnostic step I'd take would be to look at array_bytes.length, either in the debugger or via logging. I strongly suspect that you'll find it's 5. Once you've established that, you need to work out why it's 5, which has nothing to do with the calls to reading from the input stream.

Also note that this line is fundamentally wrong:

number_bytesread += array_bytes.length;

It should be:

number_bytesread += nread;

... because you've just read nread bytes. You're also sending send_package which appears to have nothing to do with the data you've just read.

Additionally, I suggest you start following Java naming conventions, with things like arrayBytes rather than array_bytes. (I'd just use buffer or data, mind you - but I'm pointing out that variable and names in Java are typically camelCased rather than using_underscores_for_word_breaks.)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top