System.out.println("hello world".getBytes("UTF-8"));
occasionally returns a different value, why is that??
Sorry, I'm still a noob at Java.
This code prints an array (byte[]), but there is no standard array printing in Java. So instead of printing the content of the array, the code displays some cryptic memory reference to the array. Eg "[B#6bbc4459". This information is not very useful and is likely to change between programm executions.
If you want to display the content of the array, you must iterate through it.
You're printing the result of calling toString() on a byte array. That doesn't show you the contents, as arrays don't override toString() - it's just showing you something like [B#ABCDEF01 where the [B shows that it's a byte array, and the value after the # is a hash code.
If you want to show the byte array contents as numbers, you want something like Arrays.toString:
byte[] data = "hello world".getBytes("UTF-8");
System.out.println(Arrays.toString(data));
Related
I currently ran into a actually quite weird problem with the put method of java.nio.bytebuffer and I wondered if you might know the answer to it, so let's get to it.
My goal is it to concatenate some data to a bytebuffer. The problem is after I call the put method it always adds a 0 after the byte array.
Here is the method which has those side effects:
public ByteBuffer toByteBuffer() {
ByteBuffer buffer = ByteBuffer.allocateDirect(1024));
buffer.put(type.name().getBytes()); // 0 added here
data.forEach((key, value) -> {
buffer.putChar('|');
buffer.put(key.getBytes()); // 0 added here
buffer.putChar('=');
buffer.put(value.getBytes()); // 0 added here
});
buffer.flip();
return buffer;
}
Expected Output should look something like this:
ClientData|OAT=14.9926405|FQRIGHT=39.689075|.....
Actual Ouptut where _ represents the 0s:
ClientData_|OAT_=14.9926405_|FQRIGHT_=39.689075_|.....
The documentation doesn't say anything about this side effect.
Also the put method only puts a 0 in between the byte arrays but not at the very end of the buffer.
I assume the method might be wrong or at least not properly documented, but I really have no clue why it would behave that way.
I think you may be slightly misinterpreting what is happening here. I note your comment about "but not at the very end of the buffer".
The \0 is actually coming from the putChar(char) calls, not the put(byte[]) calls. As it says in the docs (emphasis added):
Writes two bytes containing the given char value, in the current byte order
The default byte order is big endian; given that the chars you are writing are in the 7-bit ASCII range, this means "the byte you want" is going to be preceded by 0x00.
If you want to write a byte, use put(byte):
buffer.put((byte) '|');
I'm confused about this issue. Platform is on win7 java8.
Sample code:
String encryptedData = "0019ZfGO0nefTb2kIuHO0M3hGO09ZfGF";
Base64.Decoder decoder = Base64.getDecoder();
byte[] dataByte = decoder.decode(encryptedData);
System.out.println(dataByte);
dataByte = decoder.decode(encryptedData);
System.out.println(dataByte);
The output:
[B#15db9742
[B#6d06d69c
The exact input got different result.
Don't know if there's anyway to clear the status and make the result consistent every time?
Thanks!
In Java, arrays don't override toString(), so if you try to print one directly, you get the "className + # + the hex of the hashCode of the array", as defined by Object.toString()
Note:Just printing the array by reference variable means you are calling the toString() method of that array object.
As decoder.decode(encryptedData) returns a new byte[] every-time, therefore it gives a different value when you just print the reference variable.
Ex: System.out.println(dataByte);//output:[B#15db9742
You can use the standard library functions to print the contains of the array. There are many ways to achieve this. Just some examples are below:
System.out.println(Arrays.toString(dataByte));
System.out.println(dataByte.toList());
When debugging a java program in Eclipse, I can see (e.g. in the Variables view) the content of an arbitrary array, see the picture bellow (with the ByteArrayInputStream.buf field).
But I cannot find the array length field anywhere. Is there a way to show the length of an array in Eclipse debugger? How can I do it?
You can use the "Expressions" view and evaluate the length member:
Keep in mind that the last index is one less than the length!
While this works for public array members, it seems that an explicit cast is required for protected members. Consider the following code:
...
ByteArrayInputStream is = new ByteArrayInputStream(new byte[1769]);
...
Now, when evaluating is.buf, the Expressions view shows a dump of the array as shown in the question, but evaluating is.buf.length fails with <error(s)_during_the_evaluation>. If we add an explicit cast to ByteArrayInputStream, the evaluation works:
Thank you #ThorbjørnRavnAndersen for your answer (comment). You are right, the latest array segment (in my case: [1700..1768]) holds the length.
The whole picture:
How can I pass array byte to getReader without changes data.
byte_msg = Some array byte
println(">>>" + byte_msg)
HttpServletRequest.getReader returns new BufferedReader(
new InputStreamReader(new ByteArrayInputStream(byte_msg)))
And post reciever:
byte_msg = IOUtils.toByteArray(post.request.getReader)
println("<<<" + byte_msg)
And print return. Why do I get different answers?
>>>[B#38ffd135
<<<[B#60c0c8b5
You're printing out the result of byte[].toString() - which isn't the value of the byte array... it's just the value returned by Object.toString() - [B for "byte array", # and then the hash code. You need to convert the data to hex or something like that - which you need to do explicitly. For example, you could use the Hex class from Apache Commons Codec:
String hex = new String(Hex.encode(byte_msg));
Not that if this is arbitrary binary data you should not use InputStreamReader to convert it to a string in the first place. InputStreamReader is designed for binary data which is encoded text data - and IMO you should specify the encoding, too.
If you want to transfer arbitrary binary data, you should either transfer it without any conversion into text (so see whether your post class allows that) or use something like hex or base64 to convert to/from binary data safely.
IOUtils.toByteArray creates a new ByteArrayOutputStream then uses toByteArray() which creates a new byte[] and this array being a new objects has a new object id (the hash code you see, which is different). And this happens even if the content of the array was not changed.
In this case the mere observation (via IOUtils.toByteArray) has altered the output, because this check creates a new byte[] ;)
As Jon said, check the content of the array to see if there are any changes.
In order to print the content arrays you can convert the content of array to string using :
java.util.Arrays.toString(byte[])
and then print the result to stdout.
println(">>>" + Arrays.toString(byte_msg));
j.u.Arrays documentation is here.
I'm reading a binary file and storing each record into a byte[]. Now I'd like to collect these records into a Java Vector. (So that it can grow indefinitely.) But Vector takes Objects, not primitives (or arrays of primitives, as far as I can tell).
Is there way to "box" an array of primitives, or am I going to have to rewrite my code to turn my arrays into Arrays and my bytes into Bytes?
I tried concatenating the bytes into a String, but that failed miserable, due to String.append()'s propensity to treat my bytes as ints and convert them into String-y decimal representations!!
byte[] is-an Object (all arrays are, even primitive ones). There is nothing stopping you from adding a byte[] to a Vector.
Vector<byte[]> records = new Vector<byte[]>();
byte[] firstRecord = readRecord();
records.add(firstRecord);
Though it doesn't smell like a good design. Also, you should favour passing around List (the interface) over passing around a Vector (a concrete implementation of List).
You can add all the bytes in a byte[] to a Vector<Byte> by looping through each byte.
However, I wouldn't suggest you use Vector as it is a legacy class which was replaced in Java 1.2 (1998)
You can use an ArrayList instead, but this will use 4-16 times as much memory as the original byte[].
If you cannot use TByteArrayList, I suggest you use ByteArrayOutputStream and ByteArrayInputStream.
If you absolutely cannot convert the byte's into Bytes, then you might look into a primitive collection library such as Colt. It was written for high performance scientific stuff but it has primitive collection types that you can use.
You can do:
byte[] byteArr = new byte[]{0x41, 0x43};
List<byte[]> listBytes = Arrays.asList(byteArr); // to get a list
List<byte[]> list = new Vector<byte[]>(listBytes); // to instantiate a vector
System.out.println(Arrays.toString(list.get(0)));
Update (Based on your comments)
List<byte[]> l = new Vector<byte[]>(); // to instantiate a vector
l.add(new byte[]{0x51, 0x52});
System.out.println(Arrays.toString(l.get(0)));
OUTPUT
[81, 82]
I catch what u mean,
Yes it is impossible to put array of somethings into a Vector or even into ArrayList as one element, let me explain why the following code is completely right but we misunderstand it
Vector<byte[]> records = new Vector<byte[]>();
byte[] firstRecord = readRecord();
records.add(firstRecord);
The third line of this code doesn't put the array into the Vector but instead it puts the reference firstRecord into that Vector. Then if we change the contents of firstRecord after putting it in the vector, what happen is that we change the content of the Vector because we have two references to the same thing.