有小问题,非常感谢帮助:)
我应该将字节数组转换为字符串并获取此输出字符串:“[0,0,0,0]” 之后,另一个方法应该将字符串作为输入并从第一个字节数据中检索字节数组。
我得到错误,我有number.format异常,所以我想我应该以其他方式制作convertToString方法。 这就是我到目前为止所做的:
import java.io.ByteArrayOutputStream;
import java.util.StringTokenizer;
public class byteToString {
public String convertToString(){
byte[] byteArray = new byte[] {91,79,44,32,79,44,32,79,44,32,79,93};
String holder = new String(byteArray);
return holder;
}
/*was told to use this code to convert back*/
private static byte[] toByteArray(String myString){
myString = myString.substring(0, myString.length()- 1).substring(1);
ByteArrayOutputStream myStream = new ByteArrayOutputStream();
for (StringTokenizer myTok = new StringTokenizer(myString, ","); myTok.hasMoreTokens();){
myStream.write(Byte.parseByte(myTok.nextToken().trim()));
}
return myStream.toByteArray();
}
public static void main(String[] args){
String myString = new byteToString().convertToString();
toByteArray(myString);
}
}
非常感谢!! :)
答案 0 :(得分:3)
new byte[] {91,79,44,32,79,44,32,79,44,32,79,93}
实际上[O, O, O, O]
数组哦 s 零 es!
改为使用new byte[] {91,48,44,32,48,44,32,48,44,32,48,93}
。
还要注意您可以使用:
myString = myString.substring(1, myString.length() - 1);
而不是:
myString = myString.substring(0, myString.length()- 1).substring(1);
。
效率更高。
答案 1 :(得分:0)
public class AAA {
public static final byte[] TEST_DATA = {91, 79, 44, 32, 79, 44, 32, 79, 44, 32, 79, 93};
public String convertToString(byte[] array) {
return Arrays.toString(array);
}
private static byte[] toByteArray(String myString) {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
Pattern pattern = Pattern.compile("\\D*(\\d+)");
Matcher matcher = pattern.matcher(myString);
while (matcher.find()) {
bOut.write((byte)Integer.parseInt(matcher.group(1)));
}
return bOut.toByteArray();
}
public static void main(String[] args) {
String myString = new AAA().convertToString(TEST_DATA);
byte[] bytes = toByteArray(myString);
System.out.println("Test " + (Arrays.equals(bytes, TEST_DATA) ? "passed" : "failed"));
}
}
答案 2 :(得分:0)
ByteArray to String的简单解决方案在
之下 public class ByteArrayToString {
public static void main(String args[]) {
byte[] random = new byte[] { 34, 65, 54 , 76, 66, 65, 66, 70, -10 };
String utf = new String(random, "UTF-8");
String cp1252 = new String(random, "Cp1252");
String windows1252 = new String(random, "Windows-1252");
System.out.println("String created from byte `enter code here`array in UTF-8 encoding : "+ utf);
System.out.println("byte array to String in Cp1252 encoding : " + cp1252);
System.out.println("byte array to String in Windows-1252 encoding : "+ windows1252);
}
}