master
面包骑士 2024-08-20 11:39:58 +08:00
parent 578b210800
commit 00e6b97192
1 changed files with 21 additions and 19 deletions

View File

@ -1,6 +1,7 @@
package com.muyu.common.core.text; package com.muyu.common.core.text;
import com.muyu.common.core.utils.StringUtils; import com.muyu.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
@ -15,6 +16,7 @@ import java.util.Set;
* *
* @author muyu * @author muyu
*/ */
@Slf4j
public class Convert { public class Convert {
/** /**
* <br> * <br>
@ -687,7 +689,12 @@ public class Convert {
* @return * @return
*/ */
public static String str (Object obj, String charsetName) { public static String str (Object obj, String charsetName) {
return str(obj, Charset.forName(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 * @return
*/ */
public static String str(Object obj, Charset charset) { public static String str(Object obj, Charset charset) {
if (obj == null) { if (null == obj) {
return null; return null;
} }
if (obj instanceof String) { if (obj instanceof String) {
// 如果已经是String则直接返回
return (String) obj; return (String) obj;
} else if (obj instanceof byte[]) { } else if (obj instanceof byte[] || obj instanceof Byte[]) {
// 如果是byte[]则使用charset进行编码转换 if (obj instanceof byte[]) {
return new String((byte[]) obj, charset); return str((byte[]) obj, charset);
} else if (obj instanceof Byte[]) { } else {
// 如果是Byte[]先转换为byte[],再进行编码转换 Byte[] bytes = (Byte[]) obj;
Byte[] bytes = (Byte[]) obj; int length = bytes.length;
byte[] dest = new byte[bytes.length]; byte[] dest = new byte[length];
for (int i = 0; i < bytes.length; i++) { for (int i = 0 ; i < length ; i++) {
dest[i] = bytes[i].byteValue(); // 使用byteValue()来避免自动拆箱 dest[i] = bytes[i];
}
return str(dest, charset);
} }
return new String(dest, charset);
} else if (obj instanceof ByteBuffer) { } else if (obj instanceof ByteBuffer) {
// 如果是ByteBuffer则根据position和limit进行转换 return str((ByteBuffer) obj, charset);
ByteBuffer buffer = (ByteBuffer) obj;
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes); // 从buffer中读取到字节数组
return new String(bytes, charset);
} }
// 如果都不是则调用对象的toString方法这里不使用charset
return obj.toString(); return obj.toString();
} }