master
parent
578b210800
commit
00e6b97192
|
@ -1,6 +1,7 @@
|
|||
package com.muyu.common.core.text;
|
||||
|
||||
import com.muyu.common.core.utils.StringUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
|
@ -15,6 +16,7 @@ import java.util.Set;
|
|||
*
|
||||
* @author muyu
|
||||
*/
|
||||
@Slf4j
|
||||
public class Convert {
|
||||
/**
|
||||
* 转换为字符串<br>
|
||||
|
@ -687,7 +689,12 @@ public class Convert {
|
|||
* @return 字符串
|
||||
*/
|
||||
public static String str (Object obj, String charsetName) {
|
||||
try{
|
||||
return str(obj, Charset.forName(charsetName));
|
||||
}catch (Exception exception){
|
||||
log.error("字符转换异常: [{}-{}] -> {}",obj,charsetName,exception.getMessage(),exception);
|
||||
throw new RuntimeException(exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -700,32 +707,27 @@ public class Convert {
|
|||
* @return 字符串
|
||||
*/
|
||||
public static String str(Object obj, Charset charset) {
|
||||
if (obj == null) {
|
||||
if (null == obj) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (obj instanceof String) {
|
||||
// 如果已经是String,则直接返回
|
||||
return (String) obj;
|
||||
} else if (obj instanceof byte[]) {
|
||||
// 如果是byte[],则使用charset进行编码转换
|
||||
return new String((byte[]) obj, charset);
|
||||
} else if (obj instanceof Byte[]) {
|
||||
// 如果是Byte[],先转换为byte[],再进行编码转换
|
||||
} else if (obj instanceof byte[] || obj instanceof Byte[]) {
|
||||
if (obj instanceof byte[]) {
|
||||
return str((byte[]) obj, charset);
|
||||
} else {
|
||||
Byte[] bytes = (Byte[]) obj;
|
||||
byte[] dest = new byte[bytes.length];
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
dest[i] = bytes[i].byteValue(); // 使用byteValue()来避免自动拆箱
|
||||
int length = bytes.length;
|
||||
byte[] dest = new byte[length];
|
||||
for (int i = 0 ; i < length ; i++) {
|
||||
dest[i] = bytes[i];
|
||||
}
|
||||
return str(dest, charset);
|
||||
}
|
||||
return new String(dest, charset);
|
||||
} else if (obj instanceof ByteBuffer) {
|
||||
// 如果是ByteBuffer,则根据position和limit进行转换
|
||||
ByteBuffer buffer = (ByteBuffer) obj;
|
||||
byte[] bytes = new byte[buffer.remaining()];
|
||||
buffer.get(bytes); // 从buffer中读取到字节数组
|
||||
return new String(bytes, charset);
|
||||
return str((ByteBuffer) obj, charset);
|
||||
}
|
||||
// 如果都不是,则调用对象的toString方法,这里不使用charset
|
||||
return obj.toString();
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue