String.getBytes()为多次执行返回不同的值? [英] String.getBytes() returns different values for multiple execution?
问题描述
public static void main(String[] args) {
try {
String name = "i love my country";
byte[] sigToVerify = name.getBytes();
System.out.println("file data:" + sigToVerify);
String name1 = "data";
byte[] sigToVerify1 = name1.getBytes();
System.out.println("file data1:" + sigToVerify1);
}
}
我正在尝试执行上述操作程序,但 getBytes()
为我提供了相同的字符串
的不同值。有没有办法在给定字符串执行多次时获取相同的字节?
I am trying to execute the above program but getBytes()
gives me different values for the same String
. Is there any way to get the same byte while executing multiple times for a given string?
推荐答案
System.out.println("file data:" + sigToVerify);
这里没有打印 String $ c $的值C>。正如owlstead在评论中正确指出的那样,将在字节数组
sigToVerify
上调用Object.toString()方法。导致这种格式的输出:
Here you are not printing the value of a String
. As owlstead pointed out correctly in the comments, the Object.toString() method will be invoked on the byte array sigToVerify
. Leading to an output of this format:
getClass().getName() + '@' + Integer.toHexString(hashCode())
如果你想打印数组中的每个元素,你必须循环它。
If you want to print each element in the array you have to loop through it.
byte[] bytes = "i love my country".getBytes();
for(byte b : bytes) {
System.out.println("byte = " + b);
}
甚至更简单,使用 Arrays.toString()
方法:
Or even simpler, use the Arrays.toString()
method:
System.out.println(Arrays.toString(bytes));
这篇关于String.getBytes()为多次执行返回不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!