问题
I'm making a program that needs to receive data over the internet. It's doing so using DatagramSockets and receiving DatagramPackets. This all works fine, and the byte array it receives is the exact one I would expect.
However, when I try to convert the byte array to a string, and subsequently to an integer, very strange things happen.
Running the code below gives a NumberFormatException on the parseInt
line:
String length = new String(data, 1, data.length-1);
System.out.println("length = "+length);
size = Integer.parseInt(length);
System.out.println("size = "+size);
However, when I inspect the contents of data
, I see that it just contains 55,52,49,56,53,0,0,0,0,0,0,0,0,0,0,0,0
, which is fine, it's the string "74185". This throws the exception though.
When I hardcode "74185" as the length
string, everything works nicely.
What could be going wrong here?
回答1:
Your string contains embedded \0
characters. In Java, they are part of the string, other than in C.
So you first need to find the first occurrence of \0
in the string and then take the substring up to that position.
回答2:
It fails because you're using the constructor wrong. It's String(byte\[\],index,length). First parameter data
is correct. The second one should be 0
(start of the array is 0), and third should be data.length
You can just use new String(data)
instead to use the whole array.
EDIT: as Roland Illig points out, your array contains \0
characters which ruin your number. You should either get rid of those \0
s before the call, or check the index of first \0
and use it as third parameter of the above constructor +1.
Anyway if you want to send a number, why not sending a number instead of a string that you have to parse?
来源:https://stackoverflow.com/questions/19759197/numberformatexception-for-valid-number-string