我正在尝试替换一些现有的涉及字符串变量存储的逻辑,以使用字节数组(出于安全原因)。下面有两个块方法 A() 与旧逻辑和方法 B() 与替换。但是,在相似点打印输出时,我看到字节数组的输出不同。我错过了什么吗?
public class HelloWorld{
public static void main(String []args){
System.out.println("Hello World ");
A();
B();
}
public static void A()
{
String expDetails = "";
if (true) {
String expYear = "1986";
expDetails = expYear;
}
System.out.println("Output in between "+expDetails);
// expiry month in MM
String monthStr = "";
if (true) {
String expiryMonth = "12";
int month = Integer.parseInt(expiryMonth) + 1;
expDetails += month > 9 ? String.valueOf(month) : "0" + month;
}
System.out.println("Output "+expDetails);
}
public static void B()
{
byte[] expDetailsNew = null;
if (true) {
String expYear = "1986";
expDetailsNew = expYear.getBytes();
System.out.println("Inside");
}
System.out.println("Output in between "+expDetailsNew.toString());
String monthStr = "";
if (true) {
String expiryMonth = "12";
int month = Integer.parseInt(expiryMonth) + 1;
if(month>9)
{
byte[] c = new byte[expDetailsNew.length + Integer.toString(month).length()];
System.arraycopy(expDetailsNew, 0, c, 0, expDetailsNew.length);
System.arraycopy(expDetailsNew, 0, c, expDetailsNew.length, Integer.toString(month).length());
String finalVal = new String(c);
System.out.println("Output "+finalVal);
}
}
}
}
以下是输出 -
Hello World
Output in between 1986
Output 198613
Inside
Output in between [B@6d06d69c
Output 198619
更新
根据@VGR 的回答,尝试像这样附加月份值 -
CharBuffer another = CharBuffer.allocate(2);
new Formatter(another).format("%02d", month);
expDetailsNew.append(another);
expDetailsNew.flip();
System.out.println("Output "+expDetailsNew.toString());
但是输出是空的。
慕哥9229398
Smart猫小萌
相关分类