master
parent
4bb111bb9a
commit
578b210800
|
@ -699,28 +699,33 @@ public class Convert {
|
|||
*
|
||||
* @return 字符串
|
||||
*/
|
||||
public static String str (Object obj, Charset charset) {
|
||||
if (null == obj) {
|
||||
public static String str(Object obj, Charset charset) {
|
||||
if (obj == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (obj instanceof String) {
|
||||
// 如果已经是String,则直接返回
|
||||
return (String) obj;
|
||||
} else if (obj instanceof byte[] || obj instanceof Byte[]) {
|
||||
if (obj instanceof byte[]) {
|
||||
return str((byte[]) obj, charset);
|
||||
} else {
|
||||
} else if (obj instanceof byte[]) {
|
||||
// 如果是byte[],则使用charset进行编码转换
|
||||
return new String((byte[]) obj, charset);
|
||||
} else if (obj instanceof Byte[]) {
|
||||
// 如果是Byte[],先转换为byte[],再进行编码转换
|
||||
Byte[] bytes = (Byte[]) obj;
|
||||
int length = bytes.length;
|
||||
byte[] dest = new byte[length];
|
||||
for (int i = 0 ; i < length ; i++) {
|
||||
dest[i] = bytes[i];
|
||||
}
|
||||
return str(dest, charset);
|
||||
byte[] dest = new byte[bytes.length];
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
dest[i] = bytes[i].byteValue(); // 使用byteValue()来避免自动拆箱
|
||||
}
|
||||
return new String(dest, charset);
|
||||
} else if (obj instanceof ByteBuffer) {
|
||||
return str((ByteBuffer) obj, charset);
|
||||
// 如果是ByteBuffer,则根据position和limit进行转换
|
||||
ByteBuffer buffer = (ByteBuffer) obj;
|
||||
byte[] bytes = new byte[buffer.remaining()];
|
||||
buffer.get(bytes); // 从buffer中读取到字节数组
|
||||
return new String(bytes, charset);
|
||||
}
|
||||
// 如果都不是,则调用对象的toString方法,这里不使用charset
|
||||
return obj.toString();
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue