获取字节值作为字符串
Get Byte Values as String
我有字节数组 "result",其中包含像
这样的值
[0, 1, 4, 5, 3, 2, 6, 7, 8, 9]
我想把它转换成像
这样的字符串
0,1,4,5,3,2,6,7,8,9.
我已经采取了以下方法,但没有用。
String str = new String(result, "ISO-8859-1"); Used "UTF-8" Character set also.
String str = Arrays.toString(result);
由于没有简单的方法可以将 byte[]
转换为 List<Byte>
以在 String.join()
中使用或转换为流,因此代码会比您想要的更冗长喜欢:
StringBuilder sb = new StringBuilder();
for (byte b : result)
sb.append((int) b).append(',');
String str = sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
这不是一个很好的解决方案,但这似乎可行:
/**
* @param args
*/
public static void main(String[] args) {
byte[] result = {1,2,3,4,5,6,7,8};
String str;
try {
str = new String (result, "ISO-8859-1" ).trim();
str = Arrays.toString(result).trim();
str = str.replaceAll(" ","");
System.out.println ( "str = ["+str+"]");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
}
产生输出:
str = [[1,2,3,4,5,6,7,8]]
我不明白你想要的是字符串还是字符串数组,但是 "a string":
String str = "";
for(byte a : byteArr){
str+=(char)a;
str+=",";
}
应该可以
我有字节数组 "result",其中包含像
这样的值[0, 1, 4, 5, 3, 2, 6, 7, 8, 9]
我想把它转换成像
这样的字符串0,1,4,5,3,2,6,7,8,9.
我已经采取了以下方法,但没有用。
String str = new String(result, "ISO-8859-1"); Used "UTF-8" Character set also.
String str = Arrays.toString(result);
由于没有简单的方法可以将 byte[]
转换为 List<Byte>
以在 String.join()
中使用或转换为流,因此代码会比您想要的更冗长喜欢:
StringBuilder sb = new StringBuilder();
for (byte b : result)
sb.append((int) b).append(',');
String str = sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
这不是一个很好的解决方案,但这似乎可行:
/**
* @param args
*/
public static void main(String[] args) {
byte[] result = {1,2,3,4,5,6,7,8};
String str;
try {
str = new String (result, "ISO-8859-1" ).trim();
str = Arrays.toString(result).trim();
str = str.replaceAll(" ","");
System.out.println ( "str = ["+str+"]");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
}
产生输出:
str = [[1,2,3,4,5,6,7,8]]
我不明白你想要的是字符串还是字符串数组,但是 "a string":
String str = "";
for(byte a : byteArr){
str+=(char)a;
str+=",";
}
应该可以