求助:数组变换为什么出错?
本帖最后由 proof1 于 2013-12-22 21:01:20 编辑
期望:字节数组A → 字串C → 字节数组B
为何A、B不相同?什么原因?
public class Test {
public static void main(String args[]) {
byte[] A={13,-76,-32,125,-22,1,6,-3,9};
for (int i=0; i<A.length;i++) { System.out.print(A[i]+" "); }
String C=new String(A);
System.out.println("\n"+C);
byte[] B= C.getBytes();
for (int i=0; i<B.length;i++) { System.out.print(B[i]+" "); }
}
}
[解决办法]
你在用字节数组构造String和从String获得字节数组的时候都应该指定编码方式
package anyPackage;
import java.io.UnsupportedEncodingException;
public class Test {
public static void main(String args[]) {
byte[] A = { 13, -76, -32, 125, -22, 1, 6, -3, 9 };
for (int i = 0; i < A.length; i++) {
System.out.print(A[i] + " ");
}
String C;
try {
C = new String(A,"IBM273");
System.out.println("\n" + C);
byte[] B;
B = C.getBytes(new String("IBM273"));
for (int i = 0; i < B.length; i++) {
System.out.print(B[i] + " ");
}
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}