This commit is contained in:
Looly 2023-03-23 23:50:59 +08:00
parent e81a63c6ad
commit c8309ef5fb
57 changed files with 764 additions and 505 deletions

View File

@ -2,9 +2,10 @@ package cn.hutool.core.codec;
import cn.hutool.core.codec.binary.Base16Codec; import cn.hutool.core.codec.binary.Base16Codec;
import cn.hutool.core.exceptions.UtilException; import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharUtil; import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.text.StrUtil;
import java.awt.Color; import java.awt.Color;
import java.math.BigInteger; import java.math.BigInteger;
@ -69,7 +70,7 @@ public class HexUtil {
* @return 十六进制char[] * @return 十六进制char[]
*/ */
public static char[] encodeHex(final String str, final Charset charset) { public static char[] encodeHex(final String str, final Charset charset) {
return encodeHex(StrUtil.bytes(str, charset), true); return encodeHex(ByteUtil.toBytes(str, charset), true);
} }
/** /**
@ -101,7 +102,7 @@ public class HexUtil {
* @return 十六进制String * @return 十六进制String
*/ */
public static String encodeHexStr(final String data, final Charset charset) { public static String encodeHexStr(final String data, final Charset charset) {
return encodeHexStr(StrUtil.bytes(data, charset), true); return encodeHexStr(ByteUtil.toBytes(data, charset), true);
} }
/** /**

View File

@ -1,7 +1,8 @@
package cn.hutool.core.codec.binary; package cn.hutool.core.codec.binary;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil;
import java.nio.charset.Charset; import java.nio.charset.Charset;
@ -49,7 +50,7 @@ public class Base32 {
* @return 被加密后的字符串 * @return 被加密后的字符串
*/ */
public static String encode(final String source, final Charset charset) { public static String encode(final String source, final Charset charset) {
return encode(StrUtil.bytes(source, charset)); return encode(ByteUtil.toBytes(source, charset));
} }
/** /**
@ -80,7 +81,7 @@ public class Base32 {
* @return 被加密后的字符串 * @return 被加密后的字符串
*/ */
public static String encodeHex(final String source, final Charset charset) { public static String encodeHex(final String source, final Charset charset) {
return encodeHex(StrUtil.bytes(source, charset)); return encodeHex(ByteUtil.toBytes(source, charset));
} }
//----------------------------------------------------------------------------------------- decode //----------------------------------------------------------------------------------------- decode

View File

@ -1,9 +1,10 @@
package cn.hutool.core.codec.binary; package cn.hutool.core.codec.binary;
import cn.hutool.core.io.file.FileUtil;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.io.file.FileUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
@ -39,7 +40,7 @@ public class Base62 {
* @return 被加密后的字符串 * @return 被加密后的字符串
*/ */
public static String encode(final CharSequence source, final Charset charset) { public static String encode(final CharSequence source, final Charset charset) {
return encode(StrUtil.bytes(source, charset)); return encode(ByteUtil.toBytes(source, charset));
} }
/** /**
@ -90,7 +91,7 @@ public class Base62 {
* @return 被加密后的字符串 * @return 被加密后的字符串
*/ */
public static String encodeInverted(final CharSequence source, final Charset charset) { public static String encodeInverted(final CharSequence source, final Charset charset) {
return encodeInverted(StrUtil.bytes(source, charset)); return encodeInverted(ByteUtil.toBytes(source, charset));
} }
/** /**
@ -184,7 +185,7 @@ public class Base62 {
* @return 被加密后的字符串 * @return 被加密后的字符串
*/ */
public static byte[] decode(final CharSequence base62Str) { public static byte[] decode(final CharSequence base62Str) {
return decode(StrUtil.bytes(base62Str, DEFAULT_CHARSET)); return decode(ByteUtil.toBytes(base62Str, DEFAULT_CHARSET));
} }
/** /**
@ -247,7 +248,7 @@ public class Base62 {
* @return 被加密后的字符串 * @return 被加密后的字符串
*/ */
public static byte[] decodeInverted(final CharSequence base62Str) { public static byte[] decodeInverted(final CharSequence base62Str) {
return decodeInverted(StrUtil.bytes(base62Str, DEFAULT_CHARSET)); return decodeInverted(ByteUtil.toBytes(base62Str, DEFAULT_CHARSET));
} }
/** /**

View File

@ -1,9 +1,10 @@
package cn.hutool.core.codec.binary; package cn.hutool.core.codec.binary;
import cn.hutool.core.io.file.FileUtil;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.io.file.FileUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
@ -64,7 +65,7 @@ public class Base64 {
* @return 被编码后的字符串 * @return 被编码后的字符串
*/ */
public static String encode(final CharSequence source, final Charset charset) { public static String encode(final CharSequence source, final Charset charset) {
return encode(StrUtil.bytes(source, charset)); return encode(ByteUtil.toBytes(source, charset));
} }
/** /**
@ -76,7 +77,7 @@ public class Base64 {
* @since 3.0.6 * @since 3.0.6
*/ */
public static String encodeUrlSafe(final CharSequence source, final Charset charset) { public static String encodeUrlSafe(final CharSequence source, final Charset charset) {
return encodeUrlSafe(StrUtil.bytes(source, charset)); return encodeUrlSafe(ByteUtil.toBytes(source, charset));
} }
/** /**
@ -220,7 +221,7 @@ public class Base64 {
* @return 解码后的bytes * @return 解码后的bytes
*/ */
public static byte[] decode(final CharSequence base64) { public static byte[] decode(final CharSequence base64) {
return decode(StrUtil.bytes(base64, DEFAULT_CHARSET)); return decode(ByteUtil.toBytes(base64, DEFAULT_CHARSET));
} }
/** /**
@ -245,7 +246,7 @@ public class Base64 {
return false; return false;
} }
final byte[] bytes = StrUtil.utf8Bytes(base64); final byte[] bytes = ByteUtil.toUtf8Bytes(base64);
if (bytes.length != base64.length()) { if (bytes.length != base64.length()) {
// 如果长度不相等说明存在双字节字符肯定不是Base64直接返回false // 如果长度不相等说明存在双字节字符肯定不是Base64直接返回false

View File

@ -391,11 +391,11 @@ public class CityHash implements Hash32<byte[]>, Hash64<byte[]>, Hash128<byte[]>
} }
private static long fetch64(final byte[] byteArray, final int start) { private static long fetch64(final byte[] byteArray, final int start) {
return ByteUtil.bytesToLong(byteArray, start, ByteUtil.CPU_ENDIAN); return ByteUtil.toLong(byteArray, start, ByteUtil.CPU_ENDIAN);
} }
private static int fetch32(final byte[] byteArray, final int start) { private static int fetch32(final byte[] byteArray, final int start) {
return ByteUtil.bytesToInt(byteArray, start, ByteUtil.CPU_ENDIAN); return ByteUtil.toInt(byteArray, start, ByteUtil.CPU_ENDIAN);
} }
private static long hashLen16(final long u, final long v, final long mul) { private static long hashLen16(final long u, final long v, final long mul) {

View File

@ -1,7 +1,6 @@
package cn.hutool.core.codec.hash; package cn.hutool.core.codec.hash;
import cn.hutool.core.codec.Number128; import cn.hutool.core.codec.Number128;
import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil; import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
@ -60,7 +59,7 @@ public class MurmurHash implements Hash32<byte[]>, Hash64<byte[]>, Hash128<byte[
* @return Hash值 * @return Hash值
*/ */
public int hash32(final CharSequence data) { public int hash32(final CharSequence data) {
return hash32(StrUtil.bytes(data, DEFAULT_CHARSET)); return hash32(ByteUtil.toBytes(data, DEFAULT_CHARSET));
} }
/** /**
@ -102,7 +101,7 @@ public class MurmurHash implements Hash32<byte[]>, Hash64<byte[]>, Hash128<byte[
// body // body
for (int i = 0; i < nblocks; i++) { for (int i = 0; i < nblocks; i++) {
final int i4 = offset + (i << 2); final int i4 = offset + (i << 2);
final int k = ByteUtil.bytesToInt(data, i4, DEFAULT_ORDER); final int k = ByteUtil.toInt(data, i4, DEFAULT_ORDER);
// mix functions // mix functions
hash = mix32(k, hash); hash = mix32(k, hash);
} }
@ -137,7 +136,7 @@ public class MurmurHash implements Hash32<byte[]>, Hash64<byte[]>, Hash128<byte[
* @return Hash值 * @return Hash值
*/ */
public long hash64(final CharSequence data) { public long hash64(final CharSequence data) {
return hash64(StrUtil.bytes(data, DEFAULT_CHARSET)); return hash64(ByteUtil.toBytes(data, DEFAULT_CHARSET));
} }
/** /**
@ -168,7 +167,7 @@ public class MurmurHash implements Hash32<byte[]>, Hash64<byte[]>, Hash128<byte[
// body // body
for (int i = 0; i < nblocks; i++) { for (int i = 0; i < nblocks; i++) {
final int i8 = i << 3; final int i8 = i << 3;
long k = ByteUtil.bytesToLong(data, i8, DEFAULT_ORDER); long k = ByteUtil.toLong(data, i8, DEFAULT_ORDER);
// mix functions // mix functions
k *= C1; k *= C1;
@ -216,7 +215,7 @@ public class MurmurHash implements Hash32<byte[]>, Hash64<byte[]>, Hash128<byte[
* @return Hash值 (2 longs) * @return Hash值 (2 longs)
*/ */
public Number128 hash128(final CharSequence data) { public Number128 hash128(final CharSequence data) {
return hash128(StrUtil.bytes(data, DEFAULT_CHARSET)); return hash128(ByteUtil.toBytes(data, DEFAULT_CHARSET));
} }
/** /**
@ -262,8 +261,8 @@ public class MurmurHash implements Hash32<byte[]>, Hash64<byte[]>, Hash128<byte[
// body // body
for (int i = 0; i < nblocks; i++) { for (int i = 0; i < nblocks; i++) {
final int i16 = offset + (i << 4); final int i16 = offset + (i << 4);
long k1 = ByteUtil.bytesToLong(data, i16, DEFAULT_ORDER); long k1 = ByteUtil.toLong(data, i16, DEFAULT_ORDER);
long k2 = ByteUtil.bytesToLong(data, i16 + 8, DEFAULT_ORDER); long k2 = ByteUtil.toLong(data, i16 + 8, DEFAULT_ORDER);
// mix functions for k1 // mix functions for k1
k1 *= C1; k1 *= C1;

View File

@ -2,34 +2,25 @@ package cn.hutool.core.compress;
import cn.hutool.core.collection.iter.EnumerationIter; import cn.hutool.core.collection.iter.EnumerationIter;
import cn.hutool.core.exceptions.UtilException; import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.io.file.FileUtil;
import cn.hutool.core.io.IORuntimeException; import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileNameUtil; import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.io.file.FileSystemUtil; import cn.hutool.core.io.file.FileSystemUtil;
import cn.hutool.core.io.file.FileUtil;
import cn.hutool.core.io.file.PathUtil; import cn.hutool.core.io.file.PathUtil;
import cn.hutool.core.io.resource.Resource; import cn.hutool.core.io.resource.Resource;
import cn.hutool.core.io.stream.FastByteArrayOutputStream; import cn.hutool.core.io.stream.FastByteArrayOutputStream;
import cn.hutool.core.io.stream.LimitedInputStream; import cn.hutool.core.io.stream.LimitedInputStream;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharUtil; import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjUtil; import cn.hutool.core.util.ObjUtil;
import java.io.BufferedInputStream; import java.io.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.file.CopyOption;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystem; import java.nio.file.FileSystem;
import java.nio.file.Files; import java.nio.file.*;
import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.List; import java.util.List;
@ -546,7 +537,7 @@ public class ZipUtil {
* @throws IORuntimeException IO异常 * @throws IORuntimeException IO异常
* @since 5.8.5 * @since 5.8.5
*/ */
public static File unzip(ZipFile zipFile, File outFile, long limit) throws IORuntimeException { public static File unzip(final ZipFile zipFile, final File outFile, final long limit) throws IORuntimeException {
if (outFile.exists() && outFile.isFile()) { if (outFile.exists() && outFile.isFile()) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
StrUtil.format("Target path [{}] exist!", outFile.getAbsolutePath())); StrUtil.format("Target path [{}] exist!", outFile.getAbsolutePath()));
@ -725,7 +716,7 @@ public class ZipUtil {
* @throws UtilException IO异常 * @throws UtilException IO异常
*/ */
public static byte[] gzip(final String content, final Charset charset) throws UtilException { public static byte[] gzip(final String content, final Charset charset) throws UtilException {
return gzip(StrUtil.bytes(content, charset)); return gzip(ByteUtil.toBytes(content, charset));
} }
/** /**
@ -844,7 +835,7 @@ public class ZipUtil {
* @since 4.1.4 * @since 4.1.4
*/ */
public static byte[] zlib(final String content, final Charset charset, final int level) { public static byte[] zlib(final String content, final Charset charset, final int level) {
return zlib(StrUtil.bytes(content, charset), level); return zlib(ByteUtil.toBytes(content, charset), level);
} }
/** /**

View File

@ -1095,7 +1095,7 @@ public class Convert {
* @since 5.6.3 * @since 5.6.3
*/ */
public static short bytesToShort(final byte[] bytes) { public static short bytesToShort(final byte[] bytes) {
return ByteUtil.bytesToShort(bytes); return ByteUtil.toShort(bytes);
} }
/** /**
@ -1107,7 +1107,7 @@ public class Convert {
* @since 5.6.3 * @since 5.6.3
*/ */
public static byte[] shortToBytes(final short shortValue) { public static byte[] shortToBytes(final short shortValue) {
return ByteUtil.shortToBytes(shortValue); return ByteUtil.toBytes(shortValue);
} }
/** /**
@ -1119,7 +1119,7 @@ public class Convert {
* @since 5.6.3 * @since 5.6.3
*/ */
public static int bytesToInt(final byte[] bytes) { public static int bytesToInt(final byte[] bytes) {
return ByteUtil.bytesToInt(bytes); return ByteUtil.toInt(bytes);
} }
/** /**
@ -1131,7 +1131,7 @@ public class Convert {
* @since 5.6.3 * @since 5.6.3
*/ */
public static byte[] intToBytes(final int intValue) { public static byte[] intToBytes(final int intValue) {
return ByteUtil.intToBytes(intValue); return ByteUtil.toBytes(intValue);
} }
/** /**
@ -1144,7 +1144,7 @@ public class Convert {
* @since 5.6.3 * @since 5.6.3
*/ */
public static byte[] longToBytes(final long longValue) { public static byte[] longToBytes(final long longValue) {
return ByteUtil.longToBytes(longValue); return ByteUtil.toBytes(longValue);
} }
/** /**
@ -1157,6 +1157,6 @@ public class Convert {
* @since 5.6.3 * @since 5.6.3
*/ */
public static long bytesToLong(final byte[] bytes) { public static long bytesToLong(final byte[] bytes) {
return ByteUtil.bytesToLong(bytes); return ByteUtil.toLong(bytes);
} }
} }

View File

@ -160,7 +160,7 @@ public class ArrayConverter extends AbstractConverter {
} }
}else if (value instanceof Number && byte.class == targetComponentType) { }else if (value instanceof Number && byte.class == targetComponentType) {
// 用户可能想序列化指定对象 // 用户可能想序列化指定对象
result = ByteUtil.numberToBytes((Number)value); result = ByteUtil.toBytes((Number)value);
} else if (value instanceof Serializable && byte.class == targetComponentType) { } else if (value instanceof Serializable && byte.class == targetComponentType) {
// 用户可能想序列化指定对象 // 用户可能想序列化指定对象
result = SerializeUtil.serialize(value); result = SerializeUtil.serialize(value);

View File

@ -90,7 +90,7 @@ public class NumberConverter extends AbstractConverter {
// since 5.7.18 // since 5.7.18
if(value instanceof byte[]){ if(value instanceof byte[]){
return ByteUtil.bytesToNumber((byte[])value, targetType, ByteUtil.DEFAULT_ORDER); return ByteUtil.toNumber((byte[])value, targetType, ByteUtil.DEFAULT_ORDER);
} }
if (Byte.class == targetType) { if (Byte.class == targetType) {

View File

@ -1,8 +1,9 @@
package cn.hutool.core.io; package cn.hutool.core.io;
import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharUtil; import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.text.StrUtil;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.CharBuffer; import java.nio.CharBuffer;
@ -236,7 +237,7 @@ public class BufferUtil {
* @since 4.5.0 * @since 4.5.0
*/ */
public static ByteBuffer of(final CharSequence data, final Charset charset) { public static ByteBuffer of(final CharSequence data, final Charset charset) {
return of(StrUtil.bytes(data, charset)); return of(ByteUtil.toBytes(data, charset));
} }
/** /**
@ -246,8 +247,8 @@ public class BufferUtil {
* @return {@link ByteBuffer} * @return {@link ByteBuffer}
* @since 4.5.0 * @since 4.5.0
*/ */
public static ByteBuffer createUtf8(final CharSequence data) { public static ByteBuffer ofUtf8(final CharSequence data) {
return of(StrUtil.utf8Bytes(data)); return of(ByteUtil.toUtf8Bytes(data));
} }
/** /**
@ -257,7 +258,7 @@ public class BufferUtil {
* @return {@link CharBuffer} * @return {@link CharBuffer}
* @since 5.5.7 * @since 5.5.7
*/ */
public static CharBuffer createCharBuffer(final int capacity) { public static CharBuffer ofCharBuffer(final int capacity) {
return CharBuffer.allocate(capacity); return CharBuffer.allocate(capacity);
} }
} }

View File

@ -12,6 +12,7 @@ import cn.hutool.core.io.stream.StreamWriter;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.func.SerConsumer; import cn.hutool.core.lang.func.SerConsumer;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
@ -522,7 +523,7 @@ public class IoUtil extends NioUtil {
if (content == null) { if (content == null) {
return null; return null;
} }
return toStream(StrUtil.bytes(content, charset)); return toStream(ByteUtil.toBytes(content, charset));
} }
/** /**

View File

@ -2,14 +2,11 @@ package cn.hutool.core.io.resource;
import cn.hutool.core.io.IORuntimeException; import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil;
import java.io.BufferedReader; import java.io.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.io.StringReader;
import java.net.URL; import java.net.URL;
import java.nio.charset.Charset; import java.nio.charset.Charset;
@ -85,7 +82,7 @@ public class CharSequenceResource implements Resource, Serializable {
@Override @Override
public byte[] readBytes() throws IORuntimeException { public byte[] readBytes() throws IORuntimeException {
return StrUtil.bytes(this.data, this.charset); return ByteUtil.toBytes(this.data, this.charset);
} }
} }

View File

@ -1,6 +1,6 @@
package cn.hutool.core.io.stream; package cn.hutool.core.io.stream;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@ -42,6 +42,6 @@ public class StrInputStream extends ByteArrayInputStream {
* @param charset 编码 * @param charset 编码
*/ */
public StrInputStream(final CharSequence str, final Charset charset) { public StrInputStream(final CharSequence str, final Charset charset) {
super(StrUtil.bytes(str, charset)); super(ByteUtil.toBytes(str, charset));
} }
} }

View File

@ -1399,6 +1399,34 @@ public class NumberUtil {
return (n > 0) && ((n & (n - 1)) == 0); return (n > 0) && ((n & (n - 1)) == 0);
} }
/**
* 解析转换数字字符串为 {@link java.lang.Integer } 规则如下
*
* <pre>
* 10x开头的视为16进制数字
* 20开头的忽略开头的0
* 3其它情况按照10进制转换
* 4空串返回0
* 5.123形式返回0按照小于0的小数对待
* 6123.56截取小数点之前的数字忽略小数部分
* 7解析失败返回默认值
* </pre>
*
* @param numberStr 数字字符串支持0x开头0开头和普通十进制
* @param defaultValue 如果解析失败, 将返回defaultValue, 允许null
* @return Integer
*/
public static Integer parseInt(final String numberStr, final Integer defaultValue) {
if (StrUtil.isNotBlank(numberStr)) {
try {
return parseInt(numberStr);
} catch (final NumberFormatException ignore) {
// ignore
}
}
return defaultValue;
}
/** /**
* 解析转换数字字符串为int型数字规则如下 * 解析转换数字字符串为int型数字规则如下
* *
@ -1422,7 +1450,7 @@ public class NumberUtil {
return 0; return 0;
} }
if(StrUtil.containsIgnoreCase(number, "E")){ if (StrUtil.containsIgnoreCase(number, "E")) {
// 科学计数法忽略支持科学计数法一般用于表示非常小和非常大的数字这类数字转换为int后精度丢失没有意义 // 科学计数法忽略支持科学计数法一般用于表示非常小和非常大的数字这类数字转换为int后精度丢失没有意义
throw new NumberFormatException(StrUtil.format("Unsupported int format: [{}]", number)); throw new NumberFormatException(StrUtil.format("Unsupported int format: [{}]", number));
} }
@ -1439,6 +1467,35 @@ public class NumberUtil {
} }
} }
/**
* 解析转换数字字符串为 {@link java.lang.Long } 规则如下
*
* <pre>
* 10x开头的视为16进制数字
* 20开头的忽略开头的0
* 3其它情况按照10进制转换
* 4空串返回0
* 5.123形式返回0按照小于0的小数对待
* 6123.56截取小数点之前的数字忽略小数部分
* 7解析失败返回默认值
* </pre>
*
* @param numberStr 数字字符串支持0x开头0开头和普通十进制
* @param defaultValue 如果解析失败, 将返回defaultValue, 允许null
* @return Long
*/
public static Long parseLong(final String numberStr, final Long defaultValue) {
if (StrUtil.isNotBlank(numberStr)) {
try {
return parseLong(numberStr);
} catch (final NumberFormatException ignore) {
// ignore
}
}
return defaultValue;
}
/** /**
* 解析转换数字字符串为long型数字规则如下 * 解析转换数字字符串为long型数字规则如下
* *
@ -1472,6 +1529,32 @@ public class NumberUtil {
} }
} }
/**
* 解析转换数字字符串为 {@link java.lang.Float } 规则如下
*
* <pre>
* 10开头的忽略开头的0
* 2空串返回0
* 3其它情况按照10进制转换
* 4.123形式返回0.123按照小于0的小数对待
* </pre>
*
* @param numberStr 数字字符串支持0x开头0开头和普通十进制
* @param defaultValue 如果解析失败, 将返回defaultValue, 允许null
* @return Float
*/
public static Float parseFloat(final String numberStr, final Float defaultValue) {
if (StrUtil.isNotBlank(numberStr)) {
try {
return parseFloat(numberStr);
} catch (final NumberFormatException ignore) {
// ignore
}
}
return defaultValue;
}
/** /**
* 解析转换数字字符串为long型数字规则如下 * 解析转换数字字符串为long型数字规则如下
* *
@ -1498,6 +1581,31 @@ public class NumberUtil {
} }
} }
/**
* 解析转换数字字符串为 {@link java.lang.Double } 规则如下
*
* <pre>
* 10开头的忽略开头的0
* 2空串返回0
* 3其它情况按照10进制转换
* 4.123形式返回0.123按照小于0的小数对待
* </pre>
*
* @param numberStr 数字字符串支持0x开头0开头和普通十进制
* @param defaultValue 如果解析失败, 将返回defaultValue, 允许null
* @return Double
*/
public static Double parseDouble(final String numberStr, final Double defaultValue) {
if (StrUtil.isNotBlank(numberStr)) {
try {
return parseDouble(numberStr);
} catch (final NumberFormatException ignore) {
// ignore
}
}
return defaultValue;
}
/** /**
* 解析转换数字字符串为long型数字规则如下 * 解析转换数字字符串为long型数字规则如下
* *
@ -1524,6 +1632,25 @@ public class NumberUtil {
} }
} }
/**
* 将指定字符串转换为{@link Number }
* 此方法不支持科学计数法
*
* @param numberStr Number字符串
* @param defaultValue 如果解析失败, 将返回defaultValue, 允许null
* @return Number对象
*/
public static Number parseNumber(final String numberStr, final Number defaultValue) {
if (StrUtil.isNotBlank(numberStr)) {
try {
return parseNumber(numberStr);
} catch (final NumberFormatException ignore) {
// ignore
}
}
return defaultValue;
}
/** /**
* 将指定字符串转换为{@link Number} 对象<br> * 将指定字符串转换为{@link Number} 对象<br>
* 此方法不支持科学计数法 * 此方法不支持科学计数法
@ -1554,114 +1681,6 @@ public class NumberUtil {
} }
} }
/**
* int值转byte数组使用大端字节序高位字节在前低位字节在后<br>
* <a href="http://www.ruanyifeng.com/blog/2016/11/byte-order.html">http://www.ruanyifeng.com/blog/2016/11/byte-order.html</a>
*
* @param value
* @return byte数组
* @since 4.4.5
*/
public static byte[] toBytes(final int value) {
final byte[] result = new byte[4];
result[0] = (byte) (value >> 24);
result[1] = (byte) (value >> 16);
result[2] = (byte) (value >> 8);
result[3] = (byte) (value /* >> 0 */);
return result;
}
/**
* byte数组转int使用大端字节序高位字节在前低位字节在后<br>
* <a href="http://www.ruanyifeng.com/blog/2016/11/byte-order.html">http://www.ruanyifeng.com/blog/2016/11/byte-order.html</a>
*
* @param bytes byte数组
* @return int
* @since 4.4.5
*/
public static int toInt(final byte[] bytes) {
return (bytes[0] & 0xff) << 24//
| (bytes[1] & 0xff) << 16//
| (bytes[2] & 0xff) << 8//
| (bytes[3] & 0xff);
}
/**
* 以无符号字节数组的形式返回传入值
*
* @param value 需要转换的值
* @return 无符号bytes
* @since 4.5.0
*/
public static byte[] toUnsignedByteArray(final BigInteger value) {
final byte[] bytes = value.toByteArray();
if (bytes[0] == 0) {
final byte[] tmp = new byte[bytes.length - 1];
System.arraycopy(bytes, 1, tmp, 0, tmp.length);
return tmp;
}
return bytes;
}
/**
* 以无符号字节数组的形式返回传入值
*
* @param length bytes长度
* @param value 需要转换的值
* @return 无符号bytes
* @since 4.5.0
*/
public static byte[] toUnsignedByteArray(final int length, final BigInteger value) {
final byte[] bytes = value.toByteArray();
if (bytes.length == length) {
return bytes;
}
final int start = bytes[0] == 0 ? 1 : 0;
final int count = bytes.length - start;
if (count > length) {
throw new IllegalArgumentException("standard length exceeded for value");
}
final byte[] tmp = new byte[length];
System.arraycopy(bytes, start, tmp, tmp.length - count, count);
return tmp;
}
/**
* 无符号bytes转{@link BigInteger}
*
* @param buf buf 无符号bytes
* @return {@link BigInteger}
* @since 4.5.0
*/
public static BigInteger fromUnsignedByteArray(final byte[] buf) {
return new BigInteger(1, buf);
}
/**
* 无符号bytes转{@link BigInteger}
*
* @param buf 无符号bytes
* @param off 起始位置
* @param length 长度
* @return {@link BigInteger}
*/
public static BigInteger fromUnsignedByteArray(final byte[] buf, final int off, final int length) {
byte[] mag = buf;
if (off != 0 || length != buf.length) {
mag = new byte[length];
System.arraycopy(buf, off, mag, 0, length);
}
return new BigInteger(1, mag);
}
/** /**
* 检查是否为有效的数字<br> * 检查是否为有效的数字<br>
* 检查Double和Float是否为无限大或者Not a Number<br> * 检查Double和Float是否为无限大或者Not a Number<br>
@ -1672,7 +1691,7 @@ public class NumberUtil {
* @since 4.6.7 * @since 4.6.7
*/ */
public static boolean isValidNumber(final Number number) { public static boolean isValidNumber(final Number number) {
if(null == number){ if (null == number) {
return false; return false;
} }
if (number instanceof Double) { if (number instanceof Double) {

View File

@ -1,5 +1,6 @@
package cn.hutool.core.net.url; package cn.hutool.core.net.url;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharUtil; import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
@ -108,7 +109,7 @@ public class URLDecoder implements Serializable {
if (null == charset) { if (null == charset) {
return str; return str;
} }
return StrUtil.str(decode(StrUtil.bytes(str, charset), isPlusToSpace), charset); return StrUtil.str(decode(ByteUtil.toBytes(str, charset), isPlusToSpace), charset);
} }
/** /**

View File

@ -12,12 +12,8 @@ import cn.hutool.core.text.finder.CharMatcherFinder;
import cn.hutool.core.text.finder.Finder; import cn.hutool.core.text.finder.Finder;
import cn.hutool.core.text.finder.StrFinder; import cn.hutool.core.text.finder.StrFinder;
import cn.hutool.core.text.split.SplitUtil; import cn.hutool.core.text.split.SplitUtil;
import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.*;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjUtil;
import java.nio.ByteBuffer;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.text.Normalizer; import java.text.Normalizer;
@ -39,6 +35,7 @@ public class CharSequenceUtil extends StrChecker {
/** /**
* 未找到的的位置表示-1表示 * 未找到的的位置表示-1表示
*
* @see Finder#INDEX_NOT_FOUND * @see Finder#INDEX_NOT_FOUND
*/ */
public static final int INDEX_NOT_FOUND = Finder.INDEX_NOT_FOUND; public static final int INDEX_NOT_FOUND = Finder.INDEX_NOT_FOUND;
@ -1610,7 +1607,7 @@ public class CharSequenceUtil extends StrChecker {
return array; return array;
} }
// ------------------------------------------------------------------------ sub // region ----- sub
/** /**
* 改进JDK subString<br> * 改进JDK subString<br>
@ -1719,7 +1716,7 @@ public class CharSequenceUtil extends StrChecker {
} }
int counterOfDoubleByte = 0; int counterOfDoubleByte = 0;
final byte[] b = bytes(str, CharsetUtil.GBK); final byte[] b = ByteUtil.toBytes(str, CharsetUtil.GBK);
if (b.length <= len) { if (b.length <= len) {
return str.toString(); return str.toString();
} }
@ -1819,9 +1816,9 @@ public class CharSequenceUtil extends StrChecker {
} }
final int toIndex; final int toIndex;
if(fromIndex < 0){ if (fromIndex < 0) {
toIndex = fromIndex - length; toIndex = fromIndex - length;
}else{ } else {
toIndex = fromIndex + length; toIndex = fromIndex + length;
} }
return sub(input, fromIndex, toIndex); return sub(input, fromIndex, toIndex);
@ -2122,8 +2119,9 @@ public class CharSequenceUtil extends StrChecker {
public static String[] subBetweenAll(final CharSequence str, final CharSequence prefixAndSuffix) { public static String[] subBetweenAll(final CharSequence str, final CharSequence prefixAndSuffix) {
return subBetweenAll(str, prefixAndSuffix, prefixAndSuffix); return subBetweenAll(str, prefixAndSuffix, prefixAndSuffix);
} }
// endregion
// ------------------------------------------------------------------------ repeat // region ----- repeat
/** /**
* 重复某个字符 * 重复某个字符
@ -2248,8 +2246,9 @@ public class CharSequenceUtil extends StrChecker {
} }
return builder.toString(); return builder.toString();
} }
// endregion
// ------------------------------------------------------------------------ equals // region ----- equals
/** /**
* 比较两个字符串大小写敏感 * 比较两个字符串大小写敏感
@ -2423,8 +2422,9 @@ public class CharSequenceUtil extends StrChecker {
return str1.toString().regionMatches(ignoreCase, start1, str2.toString(), start2, length); return str1.toString().regionMatches(ignoreCase, start1, str2.toString(), start2, length);
} }
// endregion
// ------------------------------------------------------------------------ format // region ----- format
/** /**
* 格式化文本, {} 表示占位符<br> * 格式化文本, {} 表示占位符<br>
@ -2460,68 +2460,7 @@ public class CharSequenceUtil extends StrChecker {
public static String indexedFormat(final CharSequence pattern, final Object... arguments) { public static String indexedFormat(final CharSequence pattern, final Object... arguments) {
return MessageFormat.format(pattern.toString(), arguments); return MessageFormat.format(pattern.toString(), arguments);
} }
// ------------------------------------------------------------------------ bytes // endregion
/**
* 编码字符串编码为UTF-8
*
* @param str 字符串
* @return 编码后的字节码
*/
public static byte[] utf8Bytes(final CharSequence str) {
return bytes(str, CharsetUtil.UTF_8);
}
/**
* 编码字符串<br>
* 使用系统默认编码
*
* @param str 字符串
* @return 编码后的字节码
*/
public static byte[] bytes(final CharSequence str) {
return bytes(str, Charset.defaultCharset());
}
/**
* 编码字符串
*
* @param str 字符串
* @param charset 字符集如果此字段为空则解码的结果取决于平台
* @return 编码后的字节码
*/
public static byte[] bytes(final CharSequence str, final String charset) {
return bytes(str, isBlank(charset) ? Charset.defaultCharset() : Charset.forName(charset));
}
/**
* 编码字符串
*
* @param str 字符串
* @param charset 字符集如果此字段为空则解码的结果取决于平台
* @return 编码后的字节码
*/
public static byte[] bytes(final CharSequence str, final Charset charset) {
if (str == null) {
return null;
}
if (null == charset) {
return str.toString().getBytes();
}
return str.toString().getBytes(charset);
}
/**
* 字符串转换为byteBuffer
*
* @param str 字符串
* @param charset 编码
* @return byteBuffer
*/
public static ByteBuffer byteBuffer(final CharSequence str, final Charset charset) {
return ByteBuffer.wrap(bytes(str, charset));
}
// ------------------------------------------------------------------------ wrap // ------------------------------------------------------------------------ wrap
@ -3219,7 +3158,7 @@ public class CharSequenceUtil extends StrChecker {
if (str == null || isEmpty(prefix) || startWith(str, prefix, ignoreCase)) { if (str == null || isEmpty(prefix) || startWith(str, prefix, ignoreCase)) {
return str(str); return str(str);
} }
if (prefixes != null && prefixes.length > 0) { if (ArrayUtil.isNotEmpty(prefixes)) {
for (final CharSequence s : prefixes) { for (final CharSequence s : prefixes) {
if (startWith(str, s, ignoreCase)) { if (startWith(str, s, ignoreCase)) {
return str.toString(); return str.toString();
@ -4190,4 +4129,54 @@ public class CharSequenceUtil extends StrChecker {
} }
return str + repeat(fixedChar, fixedLength); return str + repeat(fixedChar, fixedLength);
} }
/**
* 获取两个字符串的公共前缀<br>
* <pre>{@code
* commonPrefix("abb", "acc") // "a"
* }</pre>
*
* @param str1 字符串1
* @param str2 字符串2
* @return 字符串1和字符串2的公共前缀
*/
public static CharSequence commonPrefix(final CharSequence str1, final CharSequence str2) {
if (isBlank(str1) || isBlank(str2)) {
return EMPTY;
}
final int minLength = Math.min(str1.length(), str2.length());
int index = 0;
for (; index < minLength; index++) {
if (str1.charAt(index) != str2.charAt(index)) {
break;
}
}
return str1.subSequence(0, index);
}
/**
* 获取两个字符串的公共后缀<br>
* <pre>{@code
* commonSuffix("aba", "cba") // "ba"
* }</pre>
*
* @param str1 字符串1
* @param str2 字符串2
* @return 字符串1和字符串2的公共后缀
*/
public static CharSequence commonSuffix(final CharSequence str1, final CharSequence str2) {
if (isBlank(str1) || isBlank(str2)) {
return EMPTY;
}
int str1Index = str1.length() - 1;
int str2Index = str2.length() - 1;
for (; str1Index >= 0 && str2Index >= 0; str1Index--, str2Index--) {
if (str1.charAt(str1Index) != str2.charAt(str2Index)) {
break;
}
}
return str1.subSequence(str1Index + 1, str1.length());
}
} }

View File

@ -102,6 +102,7 @@ public class StrUtil extends CharSequenceUtil implements StrPool {
} }
} }
// region ----- str
/** /**
* 将对象转为字符串<br> * 将对象转为字符串<br>
* *
@ -238,6 +239,7 @@ public class StrUtil extends CharSequenceUtil implements StrPool {
} }
return charset.decode(data).toString(); return charset.decode(data).toString();
} }
// endregion
/** /**
* 调用对象的toString方法null会返回null * 调用对象的toString方法null会返回null

View File

@ -5,6 +5,7 @@ import cn.hutool.core.math.NumberUtil;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.nio.ByteOrder; import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.DoubleAdder; import java.util.concurrent.atomic.DoubleAdder;
@ -38,13 +39,41 @@ public class ByteUtil {
*/ */
public static final ByteOrder CPU_ENDIAN = "little".equals(System.getProperty("sun.cpu.endian")) ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN; public static final ByteOrder CPU_ENDIAN = "little".equals(System.getProperty("sun.cpu.endian")) ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN;
/**
* 编码字符串编码为UTF-8
*
* @param str 字符串
* @return 编码后的字节码
*/
public static byte[] toUtf8Bytes(final CharSequence str) {
return toBytes(str, CharsetUtil.UTF_8);
}
/**
* 编码字符串
*
* @param str 字符串
* @param charset 字符集如果此字段为空则解码的结果取决于平台
* @return 编码后的字节码
*/
public static byte[] toBytes(final CharSequence str, final Charset charset) {
if (str == null) {
return null;
}
if (null == charset) {
return str.toString().getBytes();
}
return str.toString().getBytes(charset);
}
/** /**
* int转byte * int转byte
* *
* @param intValue int值 * @param intValue int值
* @return byte值 * @return byte值
*/ */
public static byte intToByte(final int intValue) { public static byte toByte(final int intValue) {
return (byte) intValue; return (byte) intValue;
} }
@ -55,7 +84,7 @@ public class ByteUtil {
* @return 无符号int值 * @return 无符号int值
* @since 3.2.0 * @since 3.2.0
*/ */
public static int byteToUnsignedInt(final byte byteValue) { public static int toUnsignedInt(final byte byteValue) {
// Java 总是把 byte 当做有符处理我们可以通过将其和 0xFF 进行二进制与得到它的无符值 // Java 总是把 byte 当做有符处理我们可以通过将其和 0xFF 进行二进制与得到它的无符值
return byteValue & 0xFF; return byteValue & 0xFF;
} }
@ -67,8 +96,8 @@ public class ByteUtil {
* @param bytes byte数组 * @param bytes byte数组
* @return short值 * @return short值
*/ */
public static short bytesToShort(final byte[] bytes) { public static short toShort(final byte[] bytes) {
return bytesToShort(bytes, DEFAULT_ORDER); return toShort(bytes, DEFAULT_ORDER);
} }
/** /**
@ -79,8 +108,8 @@ public class ByteUtil {
* @param byteOrder 端序 * @param byteOrder 端序
* @return short值 * @return short值
*/ */
public static short bytesToShort(final byte[] bytes, final ByteOrder byteOrder) { public static short toShort(final byte[] bytes, final ByteOrder byteOrder) {
return bytesToShort(bytes, 0, byteOrder); return toShort(bytes, 0, byteOrder);
} }
/** /**
@ -92,7 +121,7 @@ public class ByteUtil {
* @param byteOrder 端序 * @param byteOrder 端序
* @return short值 * @return short值
*/ */
public static short bytesToShort(final byte[] bytes, final int start, final ByteOrder byteOrder) { public static short toShort(final byte[] bytes, final int start, final ByteOrder byteOrder) {
if (ByteOrder.LITTLE_ENDIAN == byteOrder) { if (ByteOrder.LITTLE_ENDIAN == byteOrder) {
//小端模式数据的高字节保存在内存的高地址中而数据的低字节保存在内存的低地址中 //小端模式数据的高字节保存在内存的高地址中而数据的低字节保存在内存的低地址中
return (short) (bytes[start] & 0xff | (bytes[start + 1] & 0xff) << Byte.SIZE); return (short) (bytes[start] & 0xff | (bytes[start + 1] & 0xff) << Byte.SIZE);
@ -108,8 +137,8 @@ public class ByteUtil {
* @param shortValue short值 * @param shortValue short值
* @return byte数组 * @return byte数组
*/ */
public static byte[] shortToBytes(final short shortValue) { public static byte[] toBytes(final short shortValue) {
return shortToBytes(shortValue, DEFAULT_ORDER); return toBytes(shortValue, DEFAULT_ORDER);
} }
/** /**
@ -120,7 +149,7 @@ public class ByteUtil {
* @param byteOrder 端序 * @param byteOrder 端序
* @return byte数组 * @return byte数组
*/ */
public static byte[] shortToBytes(final short shortValue, final ByteOrder byteOrder) { public static byte[] toBytes(final short shortValue, final ByteOrder byteOrder) {
final byte[] b = new byte[Short.BYTES]; final byte[] b = new byte[Short.BYTES];
if (ByteOrder.LITTLE_ENDIAN == byteOrder) { if (ByteOrder.LITTLE_ENDIAN == byteOrder) {
b[0] = (byte) (shortValue & 0xff); b[0] = (byte) (shortValue & 0xff);
@ -139,8 +168,8 @@ public class ByteUtil {
* @param bytes byte数组 * @param bytes byte数组
* @return int值 * @return int值
*/ */
public static int bytesToInt(final byte[] bytes) { public static int toInt(final byte[] bytes) {
return bytesToInt(bytes, DEFAULT_ORDER); return toInt(bytes, DEFAULT_ORDER);
} }
/** /**
@ -151,8 +180,8 @@ public class ByteUtil {
* @param byteOrder 端序 * @param byteOrder 端序
* @return int值 * @return int值
*/ */
public static int bytesToInt(final byte[] bytes, final ByteOrder byteOrder) { public static int toInt(final byte[] bytes, final ByteOrder byteOrder) {
return bytesToInt(bytes, 0, byteOrder); return toInt(bytes, 0, byteOrder);
} }
/** /**
@ -165,7 +194,7 @@ public class ByteUtil {
* @return int值 * @return int值
* @since 5.7.21 * @since 5.7.21
*/ */
public static int bytesToInt(final byte[] bytes, final int start, final ByteOrder byteOrder) { public static int toInt(final byte[] bytes, final int start, final ByteOrder byteOrder) {
if (ByteOrder.LITTLE_ENDIAN == byteOrder) { if (ByteOrder.LITTLE_ENDIAN == byteOrder) {
return bytes[start] & 0xFF | // return bytes[start] & 0xFF | //
(bytes[1 + start] & 0xFF) << 8 | // (bytes[1 + start] & 0xFF) << 8 | //
@ -187,8 +216,8 @@ public class ByteUtil {
* @param intValue int值 * @param intValue int值
* @return byte数组 * @return byte数组
*/ */
public static byte[] intToBytes(final int intValue) { public static byte[] toBytes(final int intValue) {
return intToBytes(intValue, DEFAULT_ORDER); return toBytes(intValue, DEFAULT_ORDER);
} }
/** /**
@ -199,7 +228,7 @@ public class ByteUtil {
* @param byteOrder 端序 * @param byteOrder 端序
* @return byte数组 * @return byte数组
*/ */
public static byte[] intToBytes(final int intValue, final ByteOrder byteOrder) { public static byte[] toBytes(final int intValue, final ByteOrder byteOrder) {
if (ByteOrder.LITTLE_ENDIAN == byteOrder) { if (ByteOrder.LITTLE_ENDIAN == byteOrder) {
return new byte[]{ // return new byte[]{ //
@ -228,8 +257,8 @@ public class ByteUtil {
* @param longValue long值 * @param longValue long值
* @return byte数组 * @return byte数组
*/ */
public static byte[] longToBytes(final long longValue) { public static byte[] toBytes(final long longValue) {
return longToBytes(longValue, DEFAULT_ORDER); return toBytes(longValue, DEFAULT_ORDER);
} }
/** /**
@ -241,7 +270,7 @@ public class ByteUtil {
* @param byteOrder 端序 * @param byteOrder 端序
* @return byte数组 * @return byte数组
*/ */
public static byte[] longToBytes(long longValue, final ByteOrder byteOrder) { public static byte[] toBytes(long longValue, final ByteOrder byteOrder) {
final byte[] result = new byte[Long.BYTES]; final byte[] result = new byte[Long.BYTES];
if (ByteOrder.LITTLE_ENDIAN == byteOrder) { if (ByteOrder.LITTLE_ENDIAN == byteOrder) {
for (int i = 0; i < result.length; i++) { for (int i = 0; i < result.length; i++) {
@ -265,8 +294,8 @@ public class ByteUtil {
* @param bytes byte数组 * @param bytes byte数组
* @return long值 * @return long值
*/ */
public static long bytesToLong(final byte[] bytes) { public static long toLong(final byte[] bytes) {
return bytesToLong(bytes, DEFAULT_ORDER); return toLong(bytes, DEFAULT_ORDER);
} }
/** /**
@ -278,8 +307,8 @@ public class ByteUtil {
* @param byteOrder 端序 * @param byteOrder 端序
* @return long值 * @return long值
*/ */
public static long bytesToLong(final byte[] bytes, final ByteOrder byteOrder) { public static long toLong(final byte[] bytes, final ByteOrder byteOrder) {
return bytesToLong(bytes, 0, byteOrder); return toLong(bytes, 0, byteOrder);
} }
/** /**
@ -293,7 +322,7 @@ public class ByteUtil {
* @return long值 * @return long值
* @since 5.7.21 * @since 5.7.21
*/ */
public static long bytesToLong(final byte[] bytes, final int start, final ByteOrder byteOrder) { public static long toLong(final byte[] bytes, final int start, final ByteOrder byteOrder) {
long values = 0; long values = 0;
if (ByteOrder.LITTLE_ENDIAN == byteOrder) { if (ByteOrder.LITTLE_ENDIAN == byteOrder) {
for (int i = (Long.BYTES - 1); i >= 0; i--) { for (int i = (Long.BYTES - 1); i >= 0; i--) {
@ -317,8 +346,8 @@ public class ByteUtil {
* @return byte数组 * @return byte数组
* @since 5.7.18 * @since 5.7.18
*/ */
public static byte[] floatToBytes(final float floatValue) { public static byte[] toBytes(final float floatValue) {
return floatToBytes(floatValue, DEFAULT_ORDER); return toBytes(floatValue, DEFAULT_ORDER);
} }
/** /**
@ -329,8 +358,8 @@ public class ByteUtil {
* @return byte数组 * @return byte数组
* @since 5.7.18 * @since 5.7.18
*/ */
public static byte[] floatToBytes(final float floatValue, final ByteOrder byteOrder) { public static byte[] toBytes(final float floatValue, final ByteOrder byteOrder) {
return intToBytes(Float.floatToIntBits(floatValue), byteOrder); return toBytes(Float.floatToIntBits(floatValue), byteOrder);
} }
/** /**
@ -341,8 +370,8 @@ public class ByteUtil {
* @return float值 * @return float值
* @since 5.7.18 * @since 5.7.18
*/ */
public static float bytesToFloat(final byte[] bytes) { public static float toFloat(final byte[] bytes) {
return bytesToFloat(bytes, DEFAULT_ORDER); return toFloat(bytes, DEFAULT_ORDER);
} }
/** /**
@ -354,8 +383,8 @@ public class ByteUtil {
* @return float值 * @return float值
* @since 5.7.18 * @since 5.7.18
*/ */
public static float bytesToFloat(final byte[] bytes, final ByteOrder byteOrder) { public static float toFloat(final byte[] bytes, final ByteOrder byteOrder) {
return Float.intBitsToFloat(bytesToInt(bytes, byteOrder)); return Float.intBitsToFloat(toInt(bytes, byteOrder));
} }
/** /**
@ -365,8 +394,8 @@ public class ByteUtil {
* @param doubleValue double值 * @param doubleValue double值
* @return byte数组 * @return byte数组
*/ */
public static byte[] doubleToBytes(final double doubleValue) { public static byte[] toBytes(final double doubleValue) {
return doubleToBytes(doubleValue, DEFAULT_ORDER); return toBytes(doubleValue, DEFAULT_ORDER);
} }
/** /**
@ -378,8 +407,8 @@ public class ByteUtil {
* @param byteOrder 端序 * @param byteOrder 端序
* @return byte数组 * @return byte数组
*/ */
public static byte[] doubleToBytes(final double doubleValue, final ByteOrder byteOrder) { public static byte[] toBytes(final double doubleValue, final ByteOrder byteOrder) {
return longToBytes(Double.doubleToLongBits(doubleValue), byteOrder); return toBytes(Double.doubleToLongBits(doubleValue), byteOrder);
} }
/** /**
@ -389,8 +418,8 @@ public class ByteUtil {
* @param bytes byte数组 * @param bytes byte数组
* @return long值 * @return long值
*/ */
public static double bytesToDouble(final byte[] bytes) { public static double toDouble(final byte[] bytes) {
return bytesToDouble(bytes, DEFAULT_ORDER); return toDouble(bytes, DEFAULT_ORDER);
} }
/** /**
@ -401,8 +430,8 @@ public class ByteUtil {
* @param byteOrder 端序 * @param byteOrder 端序
* @return long值 * @return long值
*/ */
public static double bytesToDouble(final byte[] bytes, final ByteOrder byteOrder) { public static double toDouble(final byte[] bytes, final ByteOrder byteOrder) {
return Double.longBitsToDouble(bytesToLong(bytes, byteOrder)); return Double.longBitsToDouble(toLong(bytes, byteOrder));
} }
/** /**
@ -411,8 +440,8 @@ public class ByteUtil {
* @param number 数字 * @param number 数字
* @return bytes * @return bytes
*/ */
public static byte[] numberToBytes(final Number number) { public static byte[] toBytes(final Number number) {
return numberToBytes(number, DEFAULT_ORDER); return toBytes(number, DEFAULT_ORDER);
} }
/** /**
@ -422,21 +451,23 @@ public class ByteUtil {
* @param byteOrder 端序 * @param byteOrder 端序
* @return bytes * @return bytes
*/ */
public static byte[] numberToBytes(final Number number, final ByteOrder byteOrder) { public static byte[] toBytes(final Number number, final ByteOrder byteOrder) {
if (number instanceof Byte) { if (number instanceof Byte) {
return new byte[]{number.byteValue()}; return new byte[]{number.byteValue()};
} else if (number instanceof Double) { } else if (number instanceof Double) {
return doubleToBytes((Double) number, byteOrder); return toBytes(number.doubleValue(), byteOrder);
} else if (number instanceof Long) { } else if (number instanceof Long) {
return longToBytes((Long) number, byteOrder); return toBytes(number.longValue(), byteOrder);
} else if (number instanceof Integer) { } else if (number instanceof Integer) {
return intToBytes((Integer) number, byteOrder); return ByteUtil.toBytes(number.intValue(), byteOrder);
} else if (number instanceof Short) { } else if (number instanceof Short) {
return shortToBytes((Short) number, byteOrder); return ByteUtil.toBytes(number.shortValue(), byteOrder);
} else if (number instanceof Float) { } else if (number instanceof Float) {
return floatToBytes((Float) number, byteOrder); return toBytes(number.floatValue(), byteOrder);
} else if(number instanceof BigInteger){
return ((BigInteger) number).toByteArray();
} else { } else {
return doubleToBytes(number.doubleValue(), byteOrder); return toBytes(number.doubleValue(), byteOrder);
} }
} }
@ -451,39 +482,39 @@ public class ByteUtil {
* @throws IllegalArgumentException 不支持的数字类型如用户自定义数字类型 * @throws IllegalArgumentException 不支持的数字类型如用户自定义数字类型
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T extends Number> T bytesToNumber(final byte[] bytes, final Class<T> targetClass, final ByteOrder byteOrder) throws IllegalArgumentException { public static <T extends Number> T toNumber(final byte[] bytes, final Class<T> targetClass, final ByteOrder byteOrder) throws IllegalArgumentException {
final Number number; final Number number;
if (Byte.class == targetClass) { if (Byte.class == targetClass) {
number = bytes[0]; number = bytes[0];
} else if (Short.class == targetClass) { } else if (Short.class == targetClass) {
number = bytesToShort(bytes, byteOrder); number = toShort(bytes, byteOrder);
} else if (Integer.class == targetClass) { } else if (Integer.class == targetClass) {
number = bytesToInt(bytes, byteOrder); number = toInt(bytes, byteOrder);
} else if (AtomicInteger.class == targetClass) { } else if (AtomicInteger.class == targetClass) {
number = new AtomicInteger(bytesToInt(bytes, byteOrder)); number = new AtomicInteger(toInt(bytes, byteOrder));
} else if (Long.class == targetClass) { } else if (Long.class == targetClass) {
number = bytesToLong(bytes, byteOrder); number = toLong(bytes, byteOrder);
} else if (AtomicLong.class == targetClass) { } else if (AtomicLong.class == targetClass) {
number = new AtomicLong(bytesToLong(bytes, byteOrder)); number = new AtomicLong(toLong(bytes, byteOrder));
} else if (LongAdder.class == targetClass) { } else if (LongAdder.class == targetClass) {
final LongAdder longValue = new LongAdder(); final LongAdder longValue = new LongAdder();
longValue.add(bytesToLong(bytes, byteOrder)); longValue.add(toLong(bytes, byteOrder));
number = longValue; number = longValue;
} else if (Float.class == targetClass) { } else if (Float.class == targetClass) {
number = bytesToFloat(bytes, byteOrder); number = toFloat(bytes, byteOrder);
} else if (Double.class == targetClass) { } else if (Double.class == targetClass) {
number = bytesToDouble(bytes, byteOrder); number = toDouble(bytes, byteOrder);
} else if (DoubleAdder.class == targetClass) { } else if (DoubleAdder.class == targetClass) {
final DoubleAdder doubleAdder = new DoubleAdder(); final DoubleAdder doubleAdder = new DoubleAdder();
doubleAdder.add(bytesToDouble(bytes, byteOrder)); doubleAdder.add(toDouble(bytes, byteOrder));
number = doubleAdder; number = doubleAdder;
} else if (BigDecimal.class == targetClass) { } else if (BigDecimal.class == targetClass) {
number = NumberUtil.toBigDecimal(bytesToDouble(bytes, byteOrder)); number = NumberUtil.toBigDecimal(toDouble(bytes, byteOrder));
} else if (BigInteger.class == targetClass) { } else if (BigInteger.class == targetClass) {
number = BigInteger.valueOf(bytesToLong(bytes, byteOrder)); number = BigInteger.valueOf(toLong(bytes, byteOrder));
} else if (Number.class == targetClass) { } else if (Number.class == targetClass) {
// 用户没有明确类型具体类型默认Double // 用户没有明确类型具体类型默认Double
number = bytesToDouble(bytes, byteOrder); number = toDouble(bytes, byteOrder);
} else { } else {
// 用户自定义类型不支持 // 用户自定义类型不支持
throw new IllegalArgumentException("Unsupported Number type: " + targetClass.getName()); throw new IllegalArgumentException("Unsupported Number type: " + targetClass.getName());
@ -491,4 +522,78 @@ public class ByteUtil {
return (T) number; return (T) number;
} }
/**
* 以无符号字节数组的形式返回传入值
*
* @param value 需要转换的值
* @return 无符号bytes
* @since 4.5.0
*/
public static byte[] toUnsignedByteArray(final BigInteger value) {
final byte[] bytes = value.toByteArray();
if (bytes[0] == 0) {
final byte[] tmp = new byte[bytes.length - 1];
System.arraycopy(bytes, 1, tmp, 0, tmp.length);
return tmp;
}
return bytes;
}
/**
* 以无符号字节数组的形式返回传入值
*
* @param length bytes长度
* @param value 需要转换的值
* @return 无符号bytes
* @since 4.5.0
*/
public static byte[] toUnsignedByteArray(final int length, final BigInteger value) {
final byte[] bytes = value.toByteArray();
if (bytes.length == length) {
return bytes;
}
final int start = bytes[0] == 0 ? 1 : 0;
final int count = bytes.length - start;
if (count > length) {
throw new IllegalArgumentException("standard length exceeded for value");
}
final byte[] tmp = new byte[length];
System.arraycopy(bytes, start, tmp, tmp.length - count, count);
return tmp;
}
/**
* 无符号bytes转{@link BigInteger}
*
* @param buf buf 无符号bytes
* @return {@link BigInteger}
* @since 4.5.0
*/
public static BigInteger fromUnsignedByteArray(final byte[] buf) {
return new BigInteger(1, buf);
}
/**
* 无符号bytes转{@link BigInteger}
*
* @param buf 无符号bytes
* @param off 起始位置
* @param length 长度
* @return {@link BigInteger}
*/
public static BigInteger fromUnsignedByteArray(final byte[] buf, final int off, final int length) {
byte[] mag = buf;
if (off != 0 || length != buf.length) {
mag = new byte[length];
System.arraycopy(buf, off, mag, 0, length);
}
return new BigInteger(1, mag);
}
} }

View File

@ -1,8 +1,8 @@
package cn.hutool.core.codec; package cn.hutool.core.codec;
import cn.hutool.core.codec.binary.Base32; import cn.hutool.core.codec.binary.Base32;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.text.StrUtil;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -25,7 +25,7 @@ public class Base32Test {
@Test @Test
public void hexEncodeAndDecodeTest(){ public void hexEncodeAndDecodeTest(){
final String a = "伦家是一个非常长的字符串"; final String a = "伦家是一个非常长的字符串";
final String encode = Base32.encodeHex(StrUtil.utf8Bytes(a)); final String encode = Base32.encodeHex(ByteUtil.toUtf8Bytes(a));
Assert.assertEquals("SIUADPDEMRJ9HBV4N20E9E5AT6EPTPDON3KPBFV7JA2EBBCNSUMADP5OM8======", encode); Assert.assertEquals("SIUADPDEMRJ9HBV4N20E9E5AT6EPTPDON3KPBFV7JA2EBBCNSUMADP5OM8======", encode);
String decodeStr = Base32.decodeStrHex(encode); String decodeStr = Base32.decodeStrHex(encode);

View File

@ -1,9 +1,9 @@
package cn.hutool.core.codec; package cn.hutool.core.codec;
import cn.hutool.core.codec.binary.Base64; import cn.hutool.core.codec.binary.Base64;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.text.StrUtil;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -45,7 +45,7 @@ public class Base64Test {
@Test @Test
public void encodeAndDecodeWithoutPaddingTest() { public void encodeAndDecodeWithoutPaddingTest() {
final String a = "伦家是一个非常长的字符串66"; final String a = "伦家是一个非常长的字符串66";
final String encode = Base64.encodeWithoutPadding(StrUtil.utf8Bytes(a)); final String encode = Base64.encodeWithoutPadding(ByteUtil.toUtf8Bytes(a));
Assert.assertEquals("5Lym5a625piv5LiA5Liq6Z2e5bi46ZW/55qE5a2X56ym5LiyNjY", encode); Assert.assertEquals("5Lym5a625piv5LiA5Liq6Z2e5bi46ZW/55qE5a2X56ym5LiyNjY", encode);
final String decodeStr = Base64.decodeStr(encode); final String decodeStr = Base64.decodeStr(encode);

View File

@ -1,6 +1,6 @@
package cn.hutool.core.codec.hash; package cn.hutool.core.codec.hash;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.util.ByteUtil;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -9,30 +9,30 @@ public class CityHashTest {
@Test @Test
public void hash32Test() { public void hash32Test() {
final CityHash cityHash = CityHash.INSTANCE; final CityHash cityHash = CityHash.INSTANCE;
int hv = cityHash.hash32(StrUtil.utf8Bytes("")); int hv = cityHash.hash32(ByteUtil.toUtf8Bytes(""));
Assert.assertEquals(1290029860, hv); Assert.assertEquals(1290029860, hv);
hv = cityHash.hash32(StrUtil.utf8Bytes("你好")); hv = cityHash.hash32(ByteUtil.toUtf8Bytes("你好"));
Assert.assertEquals(1374181357, hv); Assert.assertEquals(1374181357, hv);
hv = cityHash.hash32(StrUtil.utf8Bytes("见到你很高兴")); hv = cityHash.hash32(ByteUtil.toUtf8Bytes("见到你很高兴"));
Assert.assertEquals(1475516842, hv); Assert.assertEquals(1475516842, hv);
hv = cityHash.hash32(StrUtil.utf8Bytes("我们将通过生成一个大的文件的方式来检验各种方法的执行效率因为这种方式在结束的时候需要执行文件")); hv = cityHash.hash32(ByteUtil.toUtf8Bytes("我们将通过生成一个大的文件的方式来检验各种方法的执行效率因为这种方式在结束的时候需要执行文件"));
Assert.assertEquals(0x51020cae, hv); Assert.assertEquals(0x51020cae, hv);
} }
@Test @Test
public void hash64Test() { public void hash64Test() {
final CityHash cityHash = CityHash.INSTANCE; final CityHash cityHash = CityHash.INSTANCE;
long hv = cityHash.hash64(StrUtil.utf8Bytes("")); long hv = cityHash.hash64(ByteUtil.toUtf8Bytes(""));
Assert.assertEquals(-4296898700418225525L, hv); Assert.assertEquals(-4296898700418225525L, hv);
hv = cityHash.hash64(StrUtil.utf8Bytes("你好")); hv = cityHash.hash64(ByteUtil.toUtf8Bytes("你好"));
Assert.assertEquals(-4294276205456761303L, hv); Assert.assertEquals(-4294276205456761303L, hv);
hv = cityHash.hash64(StrUtil.utf8Bytes("见到你很高兴")); hv = cityHash.hash64(ByteUtil.toUtf8Bytes("见到你很高兴"));
Assert.assertEquals(272351505337503793L, hv); Assert.assertEquals(272351505337503793L, hv);
hv = cityHash.hash64(StrUtil.utf8Bytes("我们将通过生成一个大的文件的方式来检验各种方法的执行效率因为这种方式在结束的时候需要执行文件")); hv = cityHash.hash64(ByteUtil.toUtf8Bytes("我们将通过生成一个大的文件的方式来检验各种方法的执行效率因为这种方式在结束的时候需要执行文件"));
Assert.assertEquals(-8234735310919228703L, hv); Assert.assertEquals(-8234735310919228703L, hv);
} }
} }

View File

@ -1,6 +1,6 @@
package cn.hutool.core.codec.hash; package cn.hutool.core.codec.hash;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.util.ByteUtil;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -8,29 +8,29 @@ public class MurmurHashTest {
@Test @Test
public void hash32Test() { public void hash32Test() {
int hv = MurmurHash.INSTANCE.hash32(StrUtil.utf8Bytes("")); int hv = MurmurHash.INSTANCE.hash32(ByteUtil.toUtf8Bytes(""));
Assert.assertEquals(-1898877446, hv); Assert.assertEquals(-1898877446, hv);
hv = MurmurHash.INSTANCE.hash32(StrUtil.utf8Bytes("你好")); hv = MurmurHash.INSTANCE.hash32(ByteUtil.toUtf8Bytes("你好"));
Assert.assertEquals(337357348, hv); Assert.assertEquals(337357348, hv);
hv = MurmurHash.INSTANCE.hash32(StrUtil.utf8Bytes("见到你很高兴")); hv = MurmurHash.INSTANCE.hash32(ByteUtil.toUtf8Bytes("见到你很高兴"));
Assert.assertEquals(1101306141, hv); Assert.assertEquals(1101306141, hv);
hv = MurmurHash.INSTANCE.hash32(StrUtil.utf8Bytes("我们将通过生成一个大的文件的方式来检验各种方法的执行效率因为这种方式在结束的时候需要执行文件")); hv = MurmurHash.INSTANCE.hash32(ByteUtil.toUtf8Bytes("我们将通过生成一个大的文件的方式来检验各种方法的执行效率因为这种方式在结束的时候需要执行文件"));
Assert.assertEquals(-785444229, hv); Assert.assertEquals(-785444229, hv);
} }
@Test @Test
public void hash64Test() { public void hash64Test() {
long hv = MurmurHash.INSTANCE.hash64(StrUtil.utf8Bytes("")); long hv = MurmurHash.INSTANCE.hash64(ByteUtil.toUtf8Bytes(""));
Assert.assertEquals(-1349759534971957051L, hv); Assert.assertEquals(-1349759534971957051L, hv);
hv = MurmurHash.INSTANCE.hash64(StrUtil.utf8Bytes("你好")); hv = MurmurHash.INSTANCE.hash64(ByteUtil.toUtf8Bytes("你好"));
Assert.assertEquals(-7563732748897304996L, hv); Assert.assertEquals(-7563732748897304996L, hv);
hv = MurmurHash.INSTANCE.hash64(StrUtil.utf8Bytes("见到你很高兴")); hv = MurmurHash.INSTANCE.hash64(ByteUtil.toUtf8Bytes("见到你很高兴"));
Assert.assertEquals(-766658210119995316L, hv); Assert.assertEquals(-766658210119995316L, hv);
hv = MurmurHash.INSTANCE.hash64(StrUtil.utf8Bytes("我们将通过生成一个大的文件的方式来检验各种方法的执行效率因为这种方式在结束的时候需要执行文件")); hv = MurmurHash.INSTANCE.hash64(ByteUtil.toUtf8Bytes("我们将通过生成一个大的文件的方式来检验各种方法的执行效率因为这种方式在结束的时候需要执行文件"));
Assert.assertEquals(-7469283059271653317L, hv); Assert.assertEquals(-7469283059271653317L, hv);
} }
} }

View File

@ -2,7 +2,7 @@ package cn.hutool.core.codec.hash.metro;
import cn.hutool.core.codec.HexUtil; import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.codec.Number128; import cn.hutool.core.codec.Number128;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.util.ByteUtil;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -89,7 +89,7 @@ public class MetroHash128Test {
} }
static final byte[] ENDIAN = static final byte[] ENDIAN =
StrUtil.utf8Bytes("012345678901234567890123456789012345678901234567890123456789012"); ByteUtil.toUtf8Bytes("012345678901234567890123456789012345678901234567890123456789012");
@Test @Test
public void testLittleEndian() { public void testLittleEndian() {
@ -106,7 +106,7 @@ public class MetroHash128Test {
} }
static String h128(final String input) { static String h128(final String input) {
final MetroHash128 mh = MetroHash128.of(0).apply(ByteBuffer.wrap(StrUtil.utf8Bytes(input))); final MetroHash128 mh = MetroHash128.of(0).apply(ByteBuffer.wrap(ByteUtil.toUtf8Bytes(input)));
final Number128 hash = mh.get(); final Number128 hash = mh.get();
return hex(hash.getHighValue()) + hex(hash.getLowValue()); return hex(hash.getHighValue()) + hex(hash.getLowValue());
} }

View File

@ -1,7 +1,7 @@
package cn.hutool.core.codec.hash.metro; package cn.hutool.core.codec.hash.metro;
import cn.hutool.core.codec.HexUtil; import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.util.ByteUtil;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -92,7 +92,7 @@ public class MetroHash64Test {
} }
static final byte[] ENDIAN = static final byte[] ENDIAN =
StrUtil.utf8Bytes("012345678901234567890123456789012345678901234567890123456789012"); ByteUtil.toUtf8Bytes("012345678901234567890123456789012345678901234567890123456789012");
@Test @Test
public void testLittleEndian() { public void testLittleEndian() {
@ -109,7 +109,7 @@ public class MetroHash64Test {
} }
private String h64(final String value) { private String h64(final String value) {
return HexUtil.toHex(MetroHash64.of(0).hash64(StrUtil.utf8Bytes(value))).toUpperCase(); return HexUtil.toHex(MetroHash64.of(0).hash64(ByteUtil.toUtf8Bytes(value))).toUpperCase();
} }
private static String hex(final byte[] bytes){ private static String hex(final byte[] bytes){

View File

@ -3,7 +3,7 @@ package cn.hutool.core.codec.hash.metro;
import cn.hutool.core.codec.HexUtil; import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.codec.hash.CityHash; import cn.hutool.core.codec.hash.CityHash;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.RandomUtil;
import org.junit.Assert; import org.junit.Assert;
@ -17,7 +17,7 @@ public class MetroHashTest {
@Test @Test
public void testEmpty() { public void testEmpty() {
Assert.assertEquals("705fb008071e967d", HexUtil.toHex(MetroHash64.of(0).hash64(StrUtil.utf8Bytes("")))); Assert.assertEquals("705fb008071e967d", HexUtil.toHex(MetroHash64.of(0).hash64(ByteUtil.toUtf8Bytes(""))));
} }
@Test @Test
@ -60,7 +60,7 @@ public class MetroHashTest {
final long startMetro = System.currentTimeMillis(); final long startMetro = System.currentTimeMillis();
for (final String s : strArray) { for (final String s : strArray) {
MetroHash64.of(0).hash64(StrUtil.utf8Bytes(s)); MetroHash64.of(0).hash64(ByteUtil.toUtf8Bytes(s));
} }
final long endMetro = System.currentTimeMillis(); final long endMetro = System.currentTimeMillis();
@ -84,7 +84,7 @@ public class MetroHashTest {
final long startMetro = System.currentTimeMillis(); final long startMetro = System.currentTimeMillis();
for (final String s : strArray) { for (final String s : strArray) {
MetroHash128.of(0).hash128(StrUtil.utf8Bytes(s)); MetroHash128.of(0).hash128(ByteUtil.toUtf8Bytes(s));
} }
final long endMetro = System.currentTimeMillis(); final long endMetro = System.currentTimeMillis();
@ -103,6 +103,6 @@ public class MetroHashTest {
} }
private String h64(final String value) { private String h64(final String value) {
return HexUtil.toHex(MetroHash64.of(0).hash64(StrUtil.utf8Bytes(value))).toUpperCase(); return HexUtil.toHex(MetroHash64.of(0).hash64(ByteUtil.toUtf8Bytes(value))).toUpperCase();
} }
} }

View File

@ -290,7 +290,7 @@ public class ConvertTest {
public void numberToByteArrayTest(){ public void numberToByteArrayTest(){
// 测试Serializable转换为bytes调用序列化转换 // 测试Serializable转换为bytes调用序列化转换
final byte[] bytes = Convert.toPrimitiveByteArray(12L); final byte[] bytes = Convert.toPrimitiveByteArray(12L);
Assert.assertArrayEquals(ByteUtil.longToBytes(12L), bytes); Assert.assertArrayEquals(ByteUtil.toBytes(12L), bytes);
} }
@Test @Test

View File

@ -1,8 +1,8 @@
package cn.hutool.core.io.checksum; package cn.hutool.core.io.checksum;
import cn.hutool.core.io.checksum.crc16.CRC16XModem;
import cn.hutool.core.codec.HexUtil; import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.io.checksum.crc16.CRC16XModem;
import cn.hutool.core.util.ByteUtil;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -48,7 +48,7 @@ public class CrcTest {
// I3B3RV@Gitee // I3B3RV@Gitee
final String text = "000123FFFFFF"; final String text = "000123FFFFFF";
final CRC16XModem crc16 = new CRC16XModem(); final CRC16XModem crc16 = new CRC16XModem();
crc16.update(StrUtil.bytes(text)); crc16.update(ByteUtil.toUtf8Bytes(text));
final String hexValue = crc16.getHexValue(true); final String hexValue = crc16.getHexValue(true);
Assert.assertEquals("0e04", hexValue); Assert.assertEquals("0e04", hexValue);
} }

View File

@ -158,12 +158,13 @@ public class LambdaFactoryTest {
loop(count, tasks); loop(count, tasks);
} }
@SuppressWarnings("unchecked")
@Test @Test
public void testConstructor() { public void testConstructor() {
Constructor<Something> constructor = ((SerSupplier<Constructor<Something>>) Something.class::getConstructor).get(); final Constructor<Something> constructor = ((SerSupplier<Constructor<Something>>) Something.class::getConstructor).get();
Supplier<Something> constructorLambda = LambdaFactory.build(Supplier.class, constructor); final Supplier<Something> constructorLambda = LambdaFactory.build(Supplier.class, constructor);
// constructorLambda can be cache or transfer // constructorLambda can be cache or transfer
Something something = constructorLambda.get(); final Something something = constructorLambda.get();
Assert.assertEquals(Something.class, something.getClass()); Assert.assertEquals(Something.class, something.getClass());
} }

View File

@ -220,4 +220,52 @@ public class CharSequenceUtilTest {
final String str = "A5E6005700000000000000000000000000000000000000090D0100000000000001003830"; final String str = "A5E6005700000000000000000000000000000000000000090D0100000000000001003830";
Assert.assertEquals("38", StrUtil.subByLength(str,-2,2)); Assert.assertEquals("38", StrUtil.subByLength(str,-2,2));
} }
@Test
public void commonPrefixTest() {
// -------------------------- None match -----------------------
Assert.assertEquals("", CharSequenceUtil.commonPrefix("", "abc"));
Assert.assertEquals("", CharSequenceUtil.commonPrefix(null, "abc"));
Assert.assertEquals("", CharSequenceUtil.commonPrefix("abc", null));
Assert.assertEquals("", CharSequenceUtil.commonPrefix("abc", ""));
Assert.assertEquals("", CharSequenceUtil.commonPrefix("azzzj", "bzzzj"));
Assert.assertEquals("", CharSequenceUtil.commonPrefix("english中文", "french中文"));
// -------------------------- Matched -----------------------
Assert.assertEquals("name_", CharSequenceUtil.commonPrefix("name_abc", "name_efg"));
Assert.assertEquals("zzzj", CharSequenceUtil.commonPrefix("zzzja", "zzzjb"));
Assert.assertEquals("中文", CharSequenceUtil.commonPrefix("中文english", "中文french"));
}
@Test
public void commonSuffixTest() {
// -------------------------- None match -----------------------
Assert.assertEquals("", CharSequenceUtil.commonSuffix("", "abc"));
Assert.assertEquals("", CharSequenceUtil.commonSuffix(null, "abc"));
Assert.assertEquals("", CharSequenceUtil.commonSuffix("abc", null));
Assert.assertEquals("", CharSequenceUtil.commonSuffix("abc", ""));
Assert.assertEquals("", CharSequenceUtil.commonSuffix("zzzja", "zzzjb"));
Assert.assertEquals("", CharSequenceUtil.commonSuffix("中文english", "中文Korean"));
// -------------------------- Matched -----------------------
Assert.assertEquals("_name", CharSequenceUtil.commonSuffix("abc_name", "efg_name"));
Assert.assertEquals("zzzj", CharSequenceUtil.commonSuffix("abczzzj", "efgzzzj"));
Assert.assertEquals("中文", CharSequenceUtil.commonSuffix("english中文", "Korean中文"));
}
} }

View File

@ -17,18 +17,18 @@ public class ByteUtilTest {
buffer.putInt(int1); buffer.putInt(int1);
final byte[] bytesIntFromBuffer = buffer.array(); final byte[] bytesIntFromBuffer = buffer.array();
final byte[] bytesInt = ByteUtil.intToBytes(int1, ByteOrder.LITTLE_ENDIAN); final byte[] bytesInt = ByteUtil.toBytes(int1, ByteOrder.LITTLE_ENDIAN);
Assert.assertArrayEquals(bytesIntFromBuffer, bytesInt); Assert.assertArrayEquals(bytesIntFromBuffer, bytesInt);
final int int2 = ByteUtil.bytesToInt(bytesInt, ByteOrder.LITTLE_ENDIAN); final int int2 = ByteUtil.toInt(bytesInt, ByteOrder.LITTLE_ENDIAN);
Assert.assertEquals(int1, int2); Assert.assertEquals(int1, int2);
final byte[] bytesInt2 = ByteUtil.intToBytes(int1, ByteOrder.LITTLE_ENDIAN); final byte[] bytesInt2 = ByteUtil.toBytes(int1, ByteOrder.LITTLE_ENDIAN);
final int int3 = ByteUtil.bytesToInt(bytesInt2, ByteOrder.LITTLE_ENDIAN); final int int3 = ByteUtil.toInt(bytesInt2, ByteOrder.LITTLE_ENDIAN);
Assert.assertEquals(int1, int3); Assert.assertEquals(int1, int3);
final byte[] bytesInt3 = ByteUtil.intToBytes(int1, ByteOrder.LITTLE_ENDIAN); final byte[] bytesInt3 = ByteUtil.toBytes(int1, ByteOrder.LITTLE_ENDIAN);
final int int4 = ByteUtil.bytesToInt(bytesInt3, ByteOrder.LITTLE_ENDIAN); final int int4 = ByteUtil.toInt(bytesInt3, ByteOrder.LITTLE_ENDIAN);
Assert.assertEquals(int1, int4); Assert.assertEquals(int1, int4);
} }
@ -41,11 +41,11 @@ public class ByteUtilTest {
buffer.putInt(int2); buffer.putInt(int2);
final byte[] bytesIntFromBuffer = buffer.array(); final byte[] bytesIntFromBuffer = buffer.array();
final byte[] bytesInt = ByteUtil.intToBytes(int2, ByteOrder.BIG_ENDIAN); final byte[] bytesInt = ByteUtil.toBytes(int2, ByteOrder.BIG_ENDIAN);
Assert.assertArrayEquals(bytesIntFromBuffer, bytesInt); Assert.assertArrayEquals(bytesIntFromBuffer, bytesInt);
// 测试大端序 byte 数组转 int // 测试大端序 byte 数组转 int
final int int3 = ByteUtil.bytesToInt(bytesInt, ByteOrder.BIG_ENDIAN); final int int3 = ByteUtil.toInt(bytesInt, ByteOrder.BIG_ENDIAN);
Assert.assertEquals(int2, int3); Assert.assertEquals(int2, int3);
} }
@ -59,18 +59,18 @@ public class ByteUtilTest {
buffer.putLong(long1); buffer.putLong(long1);
final byte[] bytesLongFromBuffer = buffer.array(); final byte[] bytesLongFromBuffer = buffer.array();
final byte[] bytesLong = ByteUtil.longToBytes(long1, ByteOrder.LITTLE_ENDIAN); final byte[] bytesLong = ByteUtil.toBytes(long1, ByteOrder.LITTLE_ENDIAN);
Assert.assertArrayEquals(bytesLongFromBuffer, bytesLong); Assert.assertArrayEquals(bytesLongFromBuffer, bytesLong);
final long long2 = ByteUtil.bytesToLong(bytesLong, ByteOrder.LITTLE_ENDIAN); final long long2 = ByteUtil.toLong(bytesLong, ByteOrder.LITTLE_ENDIAN);
Assert.assertEquals(long1, long2); Assert.assertEquals(long1, long2);
final byte[] bytesLong2 = ByteUtil.longToBytes(long1); final byte[] bytesLong2 = ByteUtil.toBytes(long1);
final long long3 = ByteUtil.bytesToLong(bytesLong2, ByteOrder.LITTLE_ENDIAN); final long long3 = ByteUtil.toLong(bytesLong2, ByteOrder.LITTLE_ENDIAN);
Assert.assertEquals(long1, long3); Assert.assertEquals(long1, long3);
final byte[] bytesLong3 = ByteUtil.longToBytes(long1, ByteOrder.LITTLE_ENDIAN); final byte[] bytesLong3 = ByteUtil.toBytes(long1, ByteOrder.LITTLE_ENDIAN);
final long long4 = ByteUtil.bytesToLong(bytesLong3); final long long4 = ByteUtil.toLong(bytesLong3);
Assert.assertEquals(long1, long4); Assert.assertEquals(long1, long4);
} }
@ -83,10 +83,10 @@ public class ByteUtilTest {
buffer.putLong(long1); buffer.putLong(long1);
final byte[] bytesLongFromBuffer = buffer.array(); final byte[] bytesLongFromBuffer = buffer.array();
final byte[] bytesLong = ByteUtil.longToBytes(long1, ByteOrder.BIG_ENDIAN); final byte[] bytesLong = ByteUtil.toBytes(long1, ByteOrder.BIG_ENDIAN);
Assert.assertArrayEquals(bytesLongFromBuffer, bytesLong); Assert.assertArrayEquals(bytesLongFromBuffer, bytesLong);
final long long2 = ByteUtil.bytesToLong(bytesLong, ByteOrder.BIG_ENDIAN); final long long2 = ByteUtil.toLong(bytesLong, ByteOrder.BIG_ENDIAN);
Assert.assertEquals(long1, long2); Assert.assertEquals(long1, long2);
} }
@ -95,8 +95,8 @@ public class ByteUtilTest {
// 测试 long byte 数组 // 测试 long byte 数组
final float f1 = (float) RandomUtil.randomDouble(); final float f1 = (float) RandomUtil.randomDouble();
final byte[] bytesLong = ByteUtil.floatToBytes(f1, ByteOrder.LITTLE_ENDIAN); final byte[] bytesLong = ByteUtil.toBytes(f1, ByteOrder.LITTLE_ENDIAN);
final float f2 = ByteUtil.bytesToFloat(bytesLong, ByteOrder.LITTLE_ENDIAN); final float f2 = ByteUtil.toFloat(bytesLong, ByteOrder.LITTLE_ENDIAN);
Assert.assertEquals(f1, f2, 0); Assert.assertEquals(f1, f2, 0);
} }
@ -105,8 +105,8 @@ public class ByteUtilTest {
// 测试大端序 long byte 数组 // 测试大端序 long byte 数组
final float f1 = (float) RandomUtil.randomDouble(); final float f1 = (float) RandomUtil.randomDouble();
final byte[] bytesLong = ByteUtil.floatToBytes(f1, ByteOrder.BIG_ENDIAN); final byte[] bytesLong = ByteUtil.toBytes(f1, ByteOrder.BIG_ENDIAN);
final float f2 = ByteUtil.bytesToFloat(bytesLong, ByteOrder.BIG_ENDIAN); final float f2 = ByteUtil.toFloat(bytesLong, ByteOrder.BIG_ENDIAN);
Assert.assertEquals(f1, f2, 0); Assert.assertEquals(f1, f2, 0);
} }
@ -115,24 +115,24 @@ public class ByteUtilTest {
public void shortAndBytesLittleEndianTest() { public void shortAndBytesLittleEndianTest() {
final short short1 = (short) RandomUtil.randomInt(); final short short1 = (short) RandomUtil.randomInt();
final byte[] bytes = ByteUtil.shortToBytes(short1, ByteOrder.LITTLE_ENDIAN); final byte[] bytes = ByteUtil.toBytes(short1, ByteOrder.LITTLE_ENDIAN);
final short short2 = ByteUtil.bytesToShort(bytes, ByteOrder.LITTLE_ENDIAN); final short short2 = ByteUtil.toShort(bytes, ByteOrder.LITTLE_ENDIAN);
Assert.assertEquals(short2, short1); Assert.assertEquals(short2, short1);
final byte[] bytes2 = ByteUtil.shortToBytes(short1); final byte[] bytes2 = ByteUtil.toBytes(short1);
final short short3 = ByteUtil.bytesToShort(bytes2, ByteOrder.LITTLE_ENDIAN); final short short3 = ByteUtil.toShort(bytes2, ByteOrder.LITTLE_ENDIAN);
Assert.assertEquals(short3, short1); Assert.assertEquals(short3, short1);
final byte[] bytes3 = ByteUtil.shortToBytes(short1, ByteOrder.LITTLE_ENDIAN); final byte[] bytes3 = ByteUtil.toBytes(short1, ByteOrder.LITTLE_ENDIAN);
final short short4 = ByteUtil.bytesToShort(bytes3); final short short4 = ByteUtil.toShort(bytes3);
Assert.assertEquals(short4, short1); Assert.assertEquals(short4, short1);
} }
@Test @Test
public void shortAndBytesBigEndianTest() { public void shortAndBytesBigEndianTest() {
final short short1 = 122; final short short1 = 122;
final byte[] bytes = ByteUtil.shortToBytes(short1, ByteOrder.BIG_ENDIAN); final byte[] bytes = ByteUtil.toBytes(short1, ByteOrder.BIG_ENDIAN);
final short short2 = ByteUtil.bytesToShort(bytes, ByteOrder.BIG_ENDIAN); final short short2 = ByteUtil.toShort(bytes, ByteOrder.BIG_ENDIAN);
Assert.assertEquals(short2, short1); Assert.assertEquals(short2, short1);
} }
@ -140,12 +140,12 @@ public class ByteUtilTest {
@Test @Test
public void bytesToLongTest(){ public void bytesToLongTest(){
final long a = RandomUtil.randomLong(0, Long.MAX_VALUE); final long a = RandomUtil.randomLong(0, Long.MAX_VALUE);
ByteBuffer wrap = ByteBuffer.wrap(ByteUtil.longToBytes(a)); ByteBuffer wrap = ByteBuffer.wrap(ByteUtil.toBytes(a));
wrap.order(ByteOrder.LITTLE_ENDIAN); wrap.order(ByteOrder.LITTLE_ENDIAN);
long aLong = wrap.getLong(); long aLong = wrap.getLong();
Assert.assertEquals(a, aLong); Assert.assertEquals(a, aLong);
wrap = ByteBuffer.wrap(ByteUtil.longToBytes(a, ByteOrder.BIG_ENDIAN)); wrap = ByteBuffer.wrap(ByteUtil.toBytes(a, ByteOrder.BIG_ENDIAN));
wrap.order(ByteOrder.BIG_ENDIAN); wrap.order(ByteOrder.BIG_ENDIAN);
aLong = wrap.getLong(); aLong = wrap.getLong();
Assert.assertEquals(a, aLong); Assert.assertEquals(a, aLong);
@ -154,12 +154,12 @@ public class ByteUtilTest {
@Test @Test
public void bytesToIntTest(){ public void bytesToIntTest(){
final int a = RandomUtil.randomInt(0, Integer.MAX_VALUE); final int a = RandomUtil.randomInt(0, Integer.MAX_VALUE);
ByteBuffer wrap = ByteBuffer.wrap(ByteUtil.intToBytes(a)); ByteBuffer wrap = ByteBuffer.wrap(ByteUtil.toBytes(a));
wrap.order(ByteOrder.LITTLE_ENDIAN); wrap.order(ByteOrder.LITTLE_ENDIAN);
int aInt = wrap.getInt(); int aInt = wrap.getInt();
Assert.assertEquals(a, aInt); Assert.assertEquals(a, aInt);
wrap = ByteBuffer.wrap(ByteUtil.intToBytes(a, ByteOrder.BIG_ENDIAN)); wrap = ByteBuffer.wrap(ByteUtil.toBytes(a, ByteOrder.BIG_ENDIAN));
wrap.order(ByteOrder.BIG_ENDIAN); wrap.order(ByteOrder.BIG_ENDIAN);
aInt = wrap.getInt(); aInt = wrap.getInt();
Assert.assertEquals(a, aInt); Assert.assertEquals(a, aInt);
@ -169,12 +169,12 @@ public class ByteUtilTest {
public void bytesToShortTest(){ public void bytesToShortTest(){
final short a = (short) RandomUtil.randomInt(0, Short.MAX_VALUE); final short a = (short) RandomUtil.randomInt(0, Short.MAX_VALUE);
ByteBuffer wrap = ByteBuffer.wrap(ByteUtil.shortToBytes(a)); ByteBuffer wrap = ByteBuffer.wrap(ByteUtil.toBytes(a));
wrap.order(ByteOrder.LITTLE_ENDIAN); wrap.order(ByteOrder.LITTLE_ENDIAN);
short aShort = wrap.getShort(); short aShort = wrap.getShort();
Assert.assertEquals(a, aShort); Assert.assertEquals(a, aShort);
wrap = ByteBuffer.wrap(ByteUtil.shortToBytes(a, ByteOrder.BIG_ENDIAN)); wrap = ByteBuffer.wrap(ByteUtil.toBytes(a, ByteOrder.BIG_ENDIAN));
wrap.order(ByteOrder.BIG_ENDIAN); wrap.order(ByteOrder.BIG_ENDIAN);
aShort = wrap.getShort(); aShort = wrap.getShort();
Assert.assertEquals(a, aShort); Assert.assertEquals(a, aShort);

View File

@ -1,7 +1,6 @@
package cn.hutool.core.util; package cn.hutool.core.util;
import cn.hutool.core.codec.hash.HashUtil; import cn.hutool.core.codec.hash.HashUtil;
import cn.hutool.core.text.StrUtil;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -10,7 +9,7 @@ public class HashUtilTest {
@Test @Test
public void cityHash128Test(){ public void cityHash128Test(){
final String s="Google发布的Hash计算算法CityHash64 与 CityHash128"; final String s="Google发布的Hash计算算法CityHash64 与 CityHash128";
final long[] hash = HashUtil.cityHash128(StrUtil.utf8Bytes(s)); final long[] hash = HashUtil.cityHash128(ByteUtil.toUtf8Bytes(s));
Assert.assertEquals(0x5944f1e788a18db0L, hash[0]); Assert.assertEquals(0x5944f1e788a18db0L, hash[0]);
Assert.assertEquals(0xc2f68d8b2bf4a5cfL, hash[1]); Assert.assertEquals(0xc2f68d8b2bf4a5cfL, hash[1]);
} }
@ -18,14 +17,14 @@ public class HashUtilTest {
@Test @Test
public void cityHash64Test(){ public void cityHash64Test(){
final String s="Google发布的Hash计算算法CityHash64 与 CityHash128"; final String s="Google发布的Hash计算算法CityHash64 与 CityHash128";
final long hash = HashUtil.cityHash64(StrUtil.utf8Bytes(s)); final long hash = HashUtil.cityHash64(ByteUtil.toUtf8Bytes(s));
Assert.assertEquals(0x1d408f2bbf967e2aL, hash); Assert.assertEquals(0x1d408f2bbf967e2aL, hash);
} }
@Test @Test
public void cityHash32Test(){ public void cityHash32Test(){
final String s="Google发布的Hash计算算法CityHash64 与 CityHash128"; final String s="Google发布的Hash计算算法CityHash64 与 CityHash128";
final int hash = HashUtil.cityHash32(StrUtil.utf8Bytes(s)); final int hash = HashUtil.cityHash32(ByteUtil.toUtf8Bytes(s));
Assert.assertEquals(0xa8944fbe, hash); Assert.assertEquals(0xa8944fbe, hash);
} }
} }

View File

@ -2,6 +2,7 @@ package cn.hutool.core.util;
import cn.hutool.core.lang.Console; import cn.hutool.core.lang.Console;
import cn.hutool.core.math.NumberUtil; import cn.hutool.core.math.NumberUtil;
import cn.hutool.core.text.StrUtil;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -10,6 +11,10 @@ import java.math.RoundingMode;
import java.text.NumberFormat; import java.text.NumberFormat;
import java.text.ParseException; import java.text.ParseException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
/** /**
* {@link NumberUtil} 单元测试类 * {@link NumberUtil} 单元测试类
* *
@ -412,6 +417,23 @@ public class NumberUtilTest {
NumberUtil.parseInt(numberStr); NumberUtil.parseInt(numberStr);
} }
@Test
public void parseIntTest5() {
// -------------------------- Parse failed -----------------------
assertThat(NumberUtil.parseInt("abc", null), nullValue());
assertThat(NumberUtil.parseInt("abc", 456), equalTo(456));
// -------------------------- Parse success -----------------------
assertThat(NumberUtil.parseInt("123.abc", 789), equalTo(123));
assertThat(NumberUtil.parseInt("123.3", null), equalTo(123));
}
@Test @Test
public void parseNumberTest() { public void parseNumberTest() {
// from 5.4.8 issue#I23ORQ@Gitee // from 5.4.8 issue#I23ORQ@Gitee
@ -432,6 +454,29 @@ public class NumberUtilTest {
Assert.assertTrue(number instanceof BigDecimal); Assert.assertTrue(number instanceof BigDecimal);
} }
@Test
public void parseNumberTest3(){
// -------------------------- Parse failed -----------------------
assertThat(NumberUtil.parseNumber("abc", null), nullValue());
assertThat(NumberUtil.parseNumber(StrUtil.EMPTY, null), nullValue());
assertThat(NumberUtil.parseNumber(StrUtil.repeat(StrUtil.SPACE, 10), null), nullValue());
assertThat(NumberUtil.parseNumber("abc", 456).intValue(), equalTo(456));
// -------------------------- Parse success -----------------------
assertThat(NumberUtil.parseNumber("123.abc", 789).intValue(), equalTo(123));
assertThat(NumberUtil.parseNumber("123.3", null).doubleValue(), equalTo(123.3D));
assertThat(NumberUtil.parseNumber("0.123.3", null).doubleValue(), equalTo(0.123D));
}
@Test @Test
public void parseHexNumberTest() { public void parseHexNumberTest() {
// 千位分隔符去掉 // 千位分隔符去掉
@ -470,6 +515,27 @@ public class NumberUtilTest {
Assert.assertEquals(0, number); Assert.assertEquals(0, number);
} }
@Test
public void parseLongTest2() {
// -------------------------- Parse failed -----------------------
final Long v1 = NumberUtil.parseLong(null, null);
assertThat(v1, nullValue());
final Long v2 = NumberUtil.parseLong(StrUtil.EMPTY, null);
assertThat(v2, nullValue());
final Long v3 = NumberUtil.parseLong("L3221", 1233L);
assertThat(v3, equalTo(1233L));
// -------------------------- Parse success -----------------------
final Long v4 = NumberUtil.parseLong("1233L", null);
assertThat(v4, equalTo(1233L));
}
@Test @Test
public void isPowerOfTwoTest() { public void isPowerOfTwoTest() {
Assert.assertFalse(NumberUtil.isPowerOfTwo(-1)); Assert.assertFalse(NumberUtil.isPowerOfTwo(-1));
@ -585,4 +651,46 @@ public class NumberUtilTest {
Assert.assertFalse(NumberUtil.isPrime(296733)); Assert.assertFalse(NumberUtil.isPrime(296733));
Assert.assertFalse(NumberUtil.isPrime(20_4123_2399)); Assert.assertFalse(NumberUtil.isPrime(20_4123_2399));
} }
@Test
public void parseFloatTest() {
// -------------------------- Parse failed -----------------------
assertThat(NumberUtil.parseFloat("abc", null), nullValue());
assertThat(NumberUtil.parseFloat("a123.33", null), nullValue());
assertThat(NumberUtil.parseFloat("..123", null), nullValue());
assertThat(NumberUtil.parseFloat(StrUtil.EMPTY, 1233F), equalTo(1233F));
// -------------------------- Parse success -----------------------
assertThat(NumberUtil.parseFloat("123.33a", null), equalTo(123.33F));
assertThat(NumberUtil.parseFloat(".123", null), equalTo(0.123F));
}
@Test
public void parseDoubleTest() {
// -------------------------- Parse failed -----------------------
assertThat(NumberUtil.parseDouble("abc", null), nullValue());
assertThat(NumberUtil.parseDouble("a123.33", null), nullValue());
assertThat(NumberUtil.parseDouble("..123", null), nullValue());
assertThat(NumberUtil.parseDouble(StrUtil.EMPTY, 1233D), equalTo(1233D));
// -------------------------- Parse success -----------------------
assertThat(NumberUtil.parseDouble("123.33a", null), equalTo(123.33D));
assertThat(NumberUtil.parseDouble(".123", null), equalTo(0.123D));
}
} }

View File

@ -120,7 +120,7 @@ public class ZipUtilTest {
@Test @Test
public void gzipTest() { public void gzipTest() {
final String data = "我是一个需要压缩的很长很长的字符串"; final String data = "我是一个需要压缩的很长很长的字符串";
final byte[] bytes = StrUtil.utf8Bytes(data); final byte[] bytes = ByteUtil.toUtf8Bytes(data);
final byte[] gzip = ZipUtil.gzip(bytes); final byte[] gzip = ZipUtil.gzip(bytes);
//保证gzip长度正常 //保证gzip长度正常
@ -134,7 +134,7 @@ public class ZipUtilTest {
@Test @Test
public void zlibTest() { public void zlibTest() {
final String data = "我是一个需要压缩的很长很长的字符串"; final String data = "我是一个需要压缩的很长很长的字符串";
final byte[] bytes = StrUtil.utf8Bytes(data); final byte[] bytes = ByteUtil.toUtf8Bytes(data);
byte[] gzip = ZipUtil.zlib(bytes, 0); byte[] gzip = ZipUtil.zlib(bytes, 0);
//保证zlib长度正常 //保证zlib长度正常
@ -203,12 +203,12 @@ public class ZipUtilTest {
@Test @Test
@Ignore @Ignore
public void sizeUnzip() throws IOException { public void sizeUnzip() throws IOException {
String zipPath = "F:\\BaiduNetdiskDownload\\demo.zip"; final String zipPath = "F:\\BaiduNetdiskDownload\\demo.zip";
String outPath = "F:\\BaiduNetdiskDownload\\test"; final String outPath = "F:\\BaiduNetdiskDownload\\test";
ZipFile zipFile = new ZipFile(zipPath, Charset.forName("GBK")); final ZipFile zipFile = new ZipFile(zipPath, Charset.forName("GBK"));
File file = new File(outPath); final File file = new File(outPath);
// 限制解压文件大小为637KB // 限制解压文件大小为637KB
long size = 637*1024L; final long size = 637*1024L;
// 限制解压文件大小为636KB // 限制解压文件大小为636KB
// long size = 636*1024L; // long size = 636*1024L;

View File

@ -4,6 +4,7 @@ import cn.hutool.core.codec.binary.Base64;
import cn.hutool.core.codec.HexUtil; import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.lang.Validator; import cn.hutool.core.lang.Validator;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.crypto.asymmetric.AsymmetricAlgorithm; import cn.hutool.crypto.asymmetric.AsymmetricAlgorithm;
import cn.hutool.crypto.asymmetric.RSA; import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.digest.DigestAlgorithm; import cn.hutool.crypto.digest.DigestAlgorithm;
@ -298,7 +299,7 @@ public class SecureUtil {
* @since 3.3.0 * @since 3.3.0
*/ */
public static HMac hmac(final HmacAlgorithm algorithm, final String key) { public static HMac hmac(final HmacAlgorithm algorithm, final String key) {
return new HMac(algorithm, StrUtil.utf8Bytes(key)); return new HMac(algorithm, ByteUtil.toUtf8Bytes(key));
} }
/** /**
@ -336,7 +337,7 @@ public class SecureUtil {
* @since 3.3.0 * @since 3.3.0
*/ */
public static HMac hmacMd5(final String key) { public static HMac hmacMd5(final String key) {
return hmacMd5(StrUtil.utf8Bytes(key)); return hmacMd5(ByteUtil.toUtf8Bytes(key));
} }
/** /**
@ -375,7 +376,7 @@ public class SecureUtil {
* @since 3.3.0 * @since 3.3.0
*/ */
public static HMac hmacSha1(final String key) { public static HMac hmacSha1(final String key) {
return hmacSha1(StrUtil.utf8Bytes(key)); return hmacSha1(ByteUtil.toUtf8Bytes(key));
} }
/** /**
@ -414,7 +415,7 @@ public class SecureUtil {
* @since 5.6.0 * @since 5.6.0
*/ */
public static HMac hmacSha256(final String key) { public static HMac hmacSha256(final String key) {
return hmacSha256(StrUtil.utf8Bytes(key)); return hmacSha256(ByteUtil.toUtf8Bytes(key));
} }
/** /**

View File

@ -1,10 +1,10 @@
package cn.hutool.crypto.asymmetric; package cn.hutool.crypto.asymmetric;
import cn.hutool.core.codec.binary.Base64;
import cn.hutool.core.codec.HexUtil; import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.codec.binary.Base64;
import cn.hutool.core.io.IORuntimeException; import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.util.ByteUtil;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.Charset; import java.nio.charset.Charset;
@ -63,7 +63,7 @@ public interface AsymmetricEncryptor {
* @return 加密后的bytes * @return 加密后的bytes
*/ */
default byte[] encrypt(final String data, final Charset charset, final KeyType keyType) { default byte[] encrypt(final String data, final Charset charset, final KeyType keyType) {
return encrypt(StrUtil.bytes(data, charset), keyType); return encrypt(ByteUtil.toBytes(data, charset), keyType);
} }
/** /**
@ -74,7 +74,7 @@ public interface AsymmetricEncryptor {
* @return 加密后的bytes * @return 加密后的bytes
*/ */
default byte[] encrypt(final String data, final KeyType keyType) { default byte[] encrypt(final String data, final KeyType keyType) {
return encrypt(StrUtil.utf8Bytes(data), keyType); return encrypt(ByteUtil.toUtf8Bytes(data), keyType);
} }
/** /**

View File

@ -1,11 +1,11 @@
package cn.hutool.crypto.asymmetric; package cn.hutool.crypto.asymmetric;
import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.codec.binary.Base64; import cn.hutool.core.codec.binary.Base64;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.text.StrUtil;
import cn.hutool.crypto.CryptoException; import cn.hutool.crypto.CryptoException;
import cn.hutool.crypto.KeyUtil; import cn.hutool.crypto.KeyUtil;
import cn.hutool.crypto.SecureUtil; import cn.hutool.crypto.SecureUtil;
@ -14,11 +14,7 @@ import cn.hutool.crypto.SignUtil;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException; import java.security.*;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.Certificate; import java.security.cert.Certificate;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.security.spec.AlgorithmParameterSpec; import java.security.spec.AlgorithmParameterSpec;
@ -198,7 +194,7 @@ public class Sign extends BaseAsymmetric<Sign> {
* @since 5.7.0 * @since 5.7.0
*/ */
public byte[] sign(final String data, final Charset charset) { public byte[] sign(final String data, final Charset charset) {
return sign(StrUtil.bytes(data, charset)); return sign(ByteUtil.toBytes(data, charset));
} }
/** /**

View File

@ -1,12 +1,12 @@
package cn.hutool.crypto.digest; package cn.hutool.crypto.digest;
import cn.hutool.core.io.file.FileUtil; import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.io.IORuntimeException; import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileUtil;
import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.text.StrUtil;
import cn.hutool.crypto.CryptoException; import cn.hutool.crypto.CryptoException;
import cn.hutool.crypto.SecureUtil; import cn.hutool.crypto.SecureUtil;
@ -169,7 +169,7 @@ public class Digester implements Serializable {
* @since 4.6.0 * @since 4.6.0
*/ */
public byte[] digest(final String data, final Charset charset) { public byte[] digest(final String data, final Charset charset) {
return digest(StrUtil.bytes(data, charset)); return digest(ByteUtil.toBytes(data, charset));
} }
/** /**

View File

@ -1,11 +1,11 @@
package cn.hutool.crypto.digest.mac; package cn.hutool.crypto.digest.mac;
import cn.hutool.core.codec.binary.Base64;
import cn.hutool.core.io.file.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.codec.HexUtil; import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.codec.binary.Base64;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.CryptoException; import cn.hutool.crypto.CryptoException;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@ -59,7 +59,7 @@ public class Mac implements Serializable {
* @return 摘要 * @return 摘要
*/ */
public byte[] digest(final String data, final Charset charset) { public byte[] digest(final String data, final Charset charset) {
return digest(StrUtil.bytes(data, charset)); return digest(ByteUtil.toBytes(data, charset));
} }
/** /**

View File

@ -1,9 +1,10 @@
package cn.hutool.crypto.symmetric; package cn.hutool.crypto.symmetric;
import cn.hutool.core.codec.binary.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.codec.HexUtil; import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.codec.binary.Base64;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.CryptoException; import cn.hutool.crypto.CryptoException;
import cn.hutool.crypto.SecureUtil; import cn.hutool.crypto.SecureUtil;
@ -51,7 +52,7 @@ public class RC4 implements Serializable {
* @throws CryptoException key长度小于5或者大于255抛出此异常 * @throws CryptoException key长度小于5或者大于255抛出此异常
*/ */
public byte[] encrypt(final String message, final Charset charset) throws CryptoException { public byte[] encrypt(final String message, final Charset charset) throws CryptoException {
return crypt(StrUtil.bytes(message, charset)); return crypt(ByteUtil.toBytes(message, charset));
} }
/** /**
@ -224,7 +225,7 @@ public class RC4 implements Serializable {
final WriteLock writeLock = this.lock.writeLock(); final WriteLock writeLock = this.lock.writeLock();
writeLock.lock(); writeLock.lock();
try { try {
this.sbox = initSBox(StrUtil.utf8Bytes(key)); this.sbox = initSBox(ByteUtil.toUtf8Bytes(key));
} finally { } finally {
writeLock.unlock(); writeLock.unlock();
} }

View File

@ -1,11 +1,11 @@
package cn.hutool.crypto.symmetric; package cn.hutool.crypto.symmetric;
import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.codec.binary.Base64; import cn.hutool.core.codec.binary.Base64;
import cn.hutool.core.io.IORuntimeException; import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.text.StrUtil;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
@ -70,7 +70,7 @@ public interface SymmetricEncryptor {
* @return 加密后的bytes * @return 加密后的bytes
*/ */
default byte[] encrypt(final String data, final Charset charset) { default byte[] encrypt(final String data, final Charset charset) {
return encrypt(StrUtil.bytes(data, charset)); return encrypt(ByteUtil.toBytes(data, charset));
} }
/** /**
@ -103,7 +103,7 @@ public interface SymmetricEncryptor {
* @return 加密后的bytes * @return 加密后的bytes
*/ */
default byte[] encrypt(final String data) { default byte[] encrypt(final String data) {
return encrypt(StrUtil.bytes(data, CharsetUtil.UTF_8)); return encrypt(ByteUtil.toBytes(data, CharsetUtil.UTF_8));
} }
/** /**

View File

@ -1,7 +1,7 @@
package cn.hutool.crypto; package cn.hutool.crypto;
import cn.hutool.core.io.resource.ResourceUtil; import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.util.ByteUtil;
import cn.hutool.crypto.asymmetric.SM2; import cn.hutool.crypto.asymmetric.SM2;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -47,8 +47,8 @@ public class OpensslKeyUtilTest {
genSm2.usePlainEncoding(); genSm2.usePlainEncoding();
final String content = "我是Hanley."; final String content = "我是Hanley.";
final byte[] sign = genSm2.sign(StrUtil.utf8Bytes(content)); final byte[] sign = genSm2.sign(ByteUtil.toUtf8Bytes(content));
final boolean verify = genSm2.verify(StrUtil.utf8Bytes(content), sign); final boolean verify = genSm2.verify(ByteUtil.toUtf8Bytes(content), sign);
Assert.assertTrue(verify); Assert.assertTrue(verify);
} }
} }

View File

@ -2,7 +2,7 @@ package cn.hutool.crypto;
import cn.hutool.core.io.file.FileUtil; import cn.hutool.core.io.file.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil; import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.util.ByteUtil;
import cn.hutool.crypto.asymmetric.KeyType; import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA; import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.asymmetric.SM2; import cn.hutool.crypto.asymmetric.SM2;
@ -86,8 +86,8 @@ public class PemUtilTest {
sm2.usePlainEncoding(); sm2.usePlainEncoding();
final String content = "我是Hanley."; final String content = "我是Hanley.";
final byte[] sign = sm2.sign(StrUtil.utf8Bytes(content)); final byte[] sign = sm2.sign(ByteUtil.toUtf8Bytes(content));
final boolean verify = sm2.verify(StrUtil.utf8Bytes(content), sign); final boolean verify = sm2.verify(ByteUtil.toUtf8Bytes(content), sign);
Assert.assertTrue(verify); Assert.assertTrue(verify);
} }
} }

View File

@ -1,11 +1,12 @@
package cn.hutool.crypto.asymmetric; package cn.hutool.crypto.asymmetric;
import cn.hutool.core.codec.binary.Base64;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.codec.HexUtil; import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.codec.binary.Base64;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.KeyUtil; import cn.hutool.crypto.KeyUtil;
import cn.hutool.crypto.SecureUtil; import cn.hutool.crypto.SecureUtil;
import org.junit.Assert; import org.junit.Assert;
@ -39,12 +40,12 @@ public class RSATest {
final RSA rsa = SecureUtil.rsa(privateKey, publicKey); final RSA rsa = SecureUtil.rsa(privateKey, publicKey);
// 公钥加密私钥解密 // 公钥加密私钥解密
final byte[] encrypt = rsa.encrypt(StrUtil.bytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PublicKey); final byte[] encrypt = rsa.encrypt(ByteUtil.toBytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PublicKey);
final byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey); final byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey);
Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt, CharsetUtil.UTF_8)); Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt, CharsetUtil.UTF_8));
// 私钥加密公钥解密 // 私钥加密公钥解密
final byte[] encrypt2 = rsa.encrypt(StrUtil.bytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PrivateKey); final byte[] encrypt2 = rsa.encrypt(ByteUtil.toBytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PrivateKey);
final byte[] decrypt2 = rsa.decrypt(encrypt2, KeyType.PublicKey); final byte[] decrypt2 = rsa.decrypt(encrypt2, KeyType.PublicKey);
Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt2, CharsetUtil.UTF_8)); Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt2, CharsetUtil.UTF_8));
} }
@ -60,13 +61,13 @@ public class RSATest {
Assert.assertNotNull(rsa.getPrivateKeyBase64()); Assert.assertNotNull(rsa.getPrivateKeyBase64());
// 公钥加密私钥解密 // 公钥加密私钥解密
final byte[] encrypt = rsa.encrypt(StrUtil.bytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PublicKey); final byte[] encrypt = rsa.encrypt(ByteUtil.toBytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PublicKey);
final byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey); final byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey);
Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt, CharsetUtil.UTF_8)); Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt, CharsetUtil.UTF_8));
// 私钥加密公钥解密 // 私钥加密公钥解密
final byte[] encrypt2 = rsa.encrypt(StrUtil.bytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PrivateKey); final byte[] encrypt2 = rsa.encrypt(ByteUtil.toBytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PrivateKey);
final byte[] decrypt2 = rsa.decrypt(encrypt2, KeyType.PublicKey); final byte[] decrypt2 = rsa.decrypt(encrypt2, KeyType.PublicKey);
Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt2, CharsetUtil.UTF_8)); Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt2, CharsetUtil.UTF_8));
} }
@ -82,13 +83,13 @@ public class RSATest {
Assert.assertNotNull(rsa.getPrivateKeyBase64()); Assert.assertNotNull(rsa.getPrivateKeyBase64());
// 公钥加密私钥解密 // 公钥加密私钥解密
final byte[] encrypt = rsa.encrypt(StrUtil.bytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PublicKey); final byte[] encrypt = rsa.encrypt(ByteUtil.toBytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PublicKey);
final byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey); final byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey);
Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt, CharsetUtil.UTF_8)); Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt, CharsetUtil.UTF_8));
// 私钥加密公钥解密 // 私钥加密公钥解密
final byte[] encrypt2 = rsa.encrypt(StrUtil.bytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PrivateKey); final byte[] encrypt2 = rsa.encrypt(ByteUtil.toBytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PrivateKey);
final byte[] decrypt2 = rsa.decrypt(encrypt2, KeyType.PublicKey); final byte[] decrypt2 = rsa.decrypt(encrypt2, KeyType.PublicKey);
Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt2, CharsetUtil.UTF_8)); Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt2, CharsetUtil.UTF_8));
} }
@ -104,13 +105,13 @@ public class RSATest {
Assert.assertNotNull(rsa.getPrivateKeyBase64()); Assert.assertNotNull(rsa.getPrivateKeyBase64());
// 公钥加密私钥解密 // 公钥加密私钥解密
final byte[] encrypt = rsa.encrypt(StrUtil.bytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PublicKey); final byte[] encrypt = rsa.encrypt(ByteUtil.toBytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PublicKey);
final byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey); final byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey);
Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt, CharsetUtil.UTF_8)); Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt, CharsetUtil.UTF_8));
// 私钥加密公钥解密 // 私钥加密公钥解密
final byte[] encrypt2 = rsa.encrypt(StrUtil.bytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PrivateKey); final byte[] encrypt2 = rsa.encrypt(ByteUtil.toBytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PrivateKey);
final byte[] decrypt2 = rsa.decrypt(encrypt2, KeyType.PublicKey); final byte[] decrypt2 = rsa.decrypt(encrypt2, KeyType.PublicKey);
Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt2, CharsetUtil.UTF_8)); Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt2, CharsetUtil.UTF_8));
} }
@ -127,12 +128,12 @@ public class RSATest {
Assert.assertNotNull(rsa.getPrivateKeyBase64()); Assert.assertNotNull(rsa.getPrivateKeyBase64());
// 公钥加密私钥解密 // 公钥加密私钥解密
final byte[] encrypt = rsa.encrypt(StrUtil.bytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PublicKey); final byte[] encrypt = rsa.encrypt(ByteUtil.toBytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PublicKey);
final byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey); final byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey);
Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt, CharsetUtil.UTF_8)); Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt, CharsetUtil.UTF_8));
// 私钥加密公钥解密 // 私钥加密公钥解密
final byte[] encrypt2 = rsa.encrypt(StrUtil.bytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PrivateKey); final byte[] encrypt2 = rsa.encrypt(ByteUtil.toBytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PrivateKey);
final byte[] decrypt2 = rsa.decrypt(encrypt2, KeyType.PublicKey); final byte[] decrypt2 = rsa.decrypt(encrypt2, KeyType.PublicKey);
Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt2, CharsetUtil.UTF_8)); Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt2, CharsetUtil.UTF_8));
} }

View File

@ -1,9 +1,10 @@
package cn.hutool.crypto.asymmetric; package cn.hutool.crypto.asymmetric;
import cn.hutool.core.codec.binary.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.codec.HexUtil; import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.codec.binary.Base64;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.ECKeyUtil; import cn.hutool.crypto.ECKeyUtil;
import cn.hutool.crypto.KeyUtil; import cn.hutool.crypto.KeyUtil;
import cn.hutool.crypto.SecureUtil; import cn.hutool.crypto.SecureUtil;
@ -54,7 +55,7 @@ public class SM2Test {
sm2.setMode(SM2Engine.Mode.C1C2C3); sm2.setMode(SM2Engine.Mode.C1C2C3);
// 公钥加密私钥解密 // 公钥加密私钥解密
final byte[] encrypt = sm2.encrypt(StrUtil.bytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PublicKey); final byte[] encrypt = sm2.encrypt(ByteUtil.toBytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PublicKey);
final byte[] decrypt = sm2.decrypt(encrypt, KeyType.PrivateKey); final byte[] decrypt = sm2.decrypt(encrypt, KeyType.PrivateKey);
Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt, CharsetUtil.UTF_8)); Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt, CharsetUtil.UTF_8));
} }
@ -70,7 +71,7 @@ public class SM2Test {
Assert.assertNotNull(sm2.getPrivateKeyBase64()); Assert.assertNotNull(sm2.getPrivateKeyBase64());
// 公钥加密私钥解密 // 公钥加密私钥解密
final byte[] encrypt = sm2.encrypt(StrUtil.bytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PublicKey); final byte[] encrypt = sm2.encrypt(ByteUtil.toBytes("我是一段测试aaaa", CharsetUtil.UTF_8), KeyType.PublicKey);
final byte[] decrypt = sm2.decrypt(encrypt, KeyType.PrivateKey); final byte[] decrypt = sm2.decrypt(encrypt, KeyType.PrivateKey);
Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt, CharsetUtil.UTF_8)); Assert.assertEquals("我是一段测试aaaa", StrUtil.str(decrypt, CharsetUtil.UTF_8));
} }
@ -137,8 +138,8 @@ public class SM2Test {
final SM2 sm2 = SmUtil.sm2(); final SM2 sm2 = SmUtil.sm2();
final byte[] sign = sm2.sign(StrUtil.utf8Bytes(content)); final byte[] sign = sm2.sign(ByteUtil.toUtf8Bytes(content));
final boolean verify = sm2.verify(StrUtil.utf8Bytes(content), sign); final boolean verify = sm2.verify(ByteUtil.toUtf8Bytes(content), sign);
Assert.assertTrue(verify); Assert.assertTrue(verify);
} }

View File

@ -1,7 +1,7 @@
package cn.hutool.crypto.asymmetric; package cn.hutool.crypto.asymmetric;
import cn.hutool.core.map.MapUtil; import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.util.ByteUtil;
import cn.hutool.crypto.SignUtil; import cn.hutool.crypto.SignUtil;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -61,7 +61,7 @@ public class SignTest {
* @param signAlgorithm 算法 * @param signAlgorithm 算法
*/ */
private void signAndVerify(final SignAlgorithm signAlgorithm) { private void signAndVerify(final SignAlgorithm signAlgorithm) {
final byte[] data = StrUtil.utf8Bytes("我是一段测试ab"); final byte[] data = ByteUtil.toUtf8Bytes("我是一段测试ab");
final Sign sign = SignUtil.sign(signAlgorithm); final Sign sign = SignUtil.sign(signAlgorithm);
// 签名 // 签名
@ -78,7 +78,7 @@ public class SignTest {
@Test @Test
public void signAndVerifyTest2() { public void signAndVerifyTest2() {
final String str = "wx2421b1c4370ec43b 支付测试 JSAPI支付测试 10000100 1add1a30ac87aa2db72f57a2375d8fec http://wxpay.wxutil.com/pub_v2/pay/notify.v2.php oUpF8uMuAJO_M2pxb1Q9zNjWeS6o 1415659990 14.23.150.211 1 JSAPI 0CB01533B8C1EF103065174F50BCA001"; final String str = "wx2421b1c4370ec43b 支付测试 JSAPI支付测试 10000100 1add1a30ac87aa2db72f57a2375d8fec http://wxpay.wxutil.com/pub_v2/pay/notify.v2.php oUpF8uMuAJO_M2pxb1Q9zNjWeS6o 1415659990 14.23.150.211 1 JSAPI 0CB01533B8C1EF103065174F50BCA001";
final byte[] data = StrUtil.utf8Bytes(str); final byte[] data = ByteUtil.toUtf8Bytes(str);
final Sign sign = SignUtil.sign(SignAlgorithm.MD5withRSA); final Sign sign = SignUtil.sign(SignAlgorithm.MD5withRSA);
// 签名 // 签名
@ -109,7 +109,7 @@ public class SignTest {
@Test @Test
public void signAndVerifyPSSTest() { public void signAndVerifyPSSTest() {
final String str = "wx2421b1c4370ec43b 支付测试 JSAPI支付测试 10000100 1add1a30ac87aa2db72f57a2375d8fec http://wxpay.wxutil.com/pub_v2/pay/notify.v2.php oUpF8uMuAJO_M2pxb1Q9zNjWeS6o 1415659990 14.23.150.211 1 JSAPI 0CB01533B8C1EF103065174F50BCA001"; final String str = "wx2421b1c4370ec43b 支付测试 JSAPI支付测试 10000100 1add1a30ac87aa2db72f57a2375d8fec http://wxpay.wxutil.com/pub_v2/pay/notify.v2.php oUpF8uMuAJO_M2pxb1Q9zNjWeS6o 1415659990 14.23.150.211 1 JSAPI 0CB01533B8C1EF103065174F50BCA001";
final byte[] data = StrUtil.utf8Bytes(str); final byte[] data = ByteUtil.toUtf8Bytes(str);
final Sign sign = SignUtil.sign(SignAlgorithm.SHA256withRSA_PSS); final Sign sign = SignUtil.sign(SignAlgorithm.SHA256withRSA_PSS);
// 签名 // 签名

View File

@ -1,6 +1,7 @@
package cn.hutool.crypto.symmetric; package cn.hutool.crypto.symmetric;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.crypto.KeyUtil; import cn.hutool.crypto.KeyUtil;
import cn.hutool.crypto.Mode; import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding; import cn.hutool.crypto.Padding;
@ -83,8 +84,8 @@ public class DesTest {
final DES des = new DES( final DES des = new DES(
Mode.CTS, Mode.CTS,
Padding.PKCS5Padding, Padding.PKCS5Padding,
StrUtil.bytes("12345678"), ByteUtil.toUtf8Bytes("12345678"),
StrUtil.bytes("11223344") ByteUtil.toUtf8Bytes("11223344")
); );
final String encryptHex = des.encryptHex(content); final String encryptHex = des.encryptHex(content);

View File

@ -4,8 +4,9 @@ import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import cn.hutool.core.net.LocalPortGenerator; import cn.hutool.core.net.LocalPortGenerator;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil;
import com.jcraft.jsch.*; import com.jcraft.jsch.*;
import java.io.IOException; import java.io.IOException;
@ -463,7 +464,7 @@ public class JschUtil {
charset = CharsetUtil.UTF_8; charset = CharsetUtil.UTF_8;
} }
final ChannelExec channel = (ChannelExec) createChannel(session, ChannelType.EXEC); final ChannelExec channel = (ChannelExec) createChannel(session, ChannelType.EXEC);
channel.setCommand(StrUtil.bytes(cmd, charset)); channel.setCommand(ByteUtil.toBytes(cmd, charset));
channel.setInputStream(null); channel.setInputStream(null);
channel.setErrStream(errStream); channel.setErrStream(errStream);
InputStream in = null; InputStream in = null;
@ -503,7 +504,7 @@ public class JschUtil {
out = shell.getOutputStream(); out = shell.getOutputStream();
in = shell.getInputStream(); in = shell.getInputStream();
out.write(StrUtil.bytes(cmd, charset)); out.write(ByteUtil.toBytes(cmd, charset));
out.flush(); out.flush();
return IoUtil.read(in, charset); return IoUtil.read(in, charset);

View File

@ -1,6 +1,6 @@
package cn.hutool.extra.servlet; package cn.hutool.extra.servlet;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.util.ByteUtil;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
@ -21,7 +21,7 @@ public class ServletUtilTest {
@Ignore @Ignore
public void writeTest() { public void writeTest() {
final HttpServletResponse response = null; final HttpServletResponse response = null;
final byte[] bytes = StrUtil.utf8Bytes("地球是我们共同的家园,需要大家珍惜."); final byte[] bytes = ByteUtil.toUtf8Bytes("地球是我们共同的家园,需要大家珍惜.");
//下载文件 //下载文件
// 这里没法直接测试直接写到这里方便调用 // 这里没法直接测试直接写到这里方便调用
@ -38,7 +38,7 @@ public class ServletUtilTest {
@Ignore @Ignore
public void jakartaWriteTest() { public void jakartaWriteTest() {
final jakarta.servlet.http.HttpServletResponse response = null; final jakarta.servlet.http.HttpServletResponse response = null;
final byte[] bytes = StrUtil.utf8Bytes("地球是我们共同的家园,需要大家珍惜."); final byte[] bytes = ByteUtil.toUtf8Bytes("地球是我们共同的家园,需要大家珍惜.");
//下载文件 //下载文件
// 这里没法直接测试直接写到这里方便调用 // 这里没法直接测试直接写到这里方便调用

View File

@ -2,7 +2,7 @@ package cn.hutool.http.client.body;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.net.url.UrlQuery; import cn.hutool.core.net.url.UrlQuery;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.util.ByteUtil;
import cn.hutool.http.meta.ContentType; import cn.hutool.http.meta.ContentType;
import java.io.OutputStream; import java.io.OutputStream;
@ -40,7 +40,7 @@ public class UrlEncodedFormBody extends FormBody<UrlEncodedFormBody> {
@Override @Override
public void write(final OutputStream out) { public void write(final OutputStream out) {
final byte[] bytes = StrUtil.bytes(UrlQuery.of(form, true).build(charset), charset); final byte[] bytes = ByteUtil.toBytes(UrlQuery.of(form, true).build(charset), charset);
IoUtil.write(out, false, bytes); IoUtil.write(out, false, bytes);
} }

View File

@ -1,10 +1,11 @@
package cn.hutool.http.server; package cn.hutool.http.server;
import cn.hutool.core.io.file.FileUtil;
import cn.hutool.core.io.IORuntimeException; import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileUtil;
import cn.hutool.core.net.url.URLEncoder; import cn.hutool.core.net.url.URLEncoder;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.ObjUtil; import cn.hutool.core.util.ObjUtil;
import cn.hutool.http.meta.ContentType; import cn.hutool.http.meta.ContentType;
import cn.hutool.http.meta.Header; import cn.hutool.http.meta.Header;
@ -12,14 +13,7 @@ import cn.hutool.http.meta.HttpStatus;
import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpExchange;
import java.io.BufferedInputStream; import java.io.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -27,6 +21,7 @@ import java.util.Map;
/** /**
* Http响应对象用于写出数据到客户端 * Http响应对象用于写出数据到客户端
*/ */
@SuppressWarnings("resource")
public class HttpServerResponse extends HttpServerBase { public class HttpServerResponse extends HttpServerBase {
private Charset charset; private Charset charset;
@ -278,7 +273,7 @@ public class HttpServerResponse extends HttpServerBase {
*/ */
public HttpServerResponse write(final String data) { public HttpServerResponse write(final String data) {
final Charset charset = ObjUtil.defaultIfNull(this.charset, DEFAULT_CHARSET); final Charset charset = ObjUtil.defaultIfNull(this.charset, DEFAULT_CHARSET);
return write(StrUtil.bytes(data, charset)); return write(ByteUtil.toBytes(data, charset));
} }
/** /**

View File

@ -1,8 +1,9 @@
package cn.hutool.json.jwt.signers; package cn.hutool.json.jwt.signers;
import cn.hutool.core.codec.binary.Base64; import cn.hutool.core.codec.binary.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.asymmetric.Sign; import cn.hutool.crypto.asymmetric.Sign;
import java.nio.charset.Charset; import java.nio.charset.Charset;
@ -63,7 +64,7 @@ public class AsymmetricJWTSigner implements JWTSigner {
@Override @Override
public boolean verify(final String headerBase64, final String payloadBase64, final String signBase64) { public boolean verify(final String headerBase64, final String payloadBase64, final String signBase64) {
return sign.verify( return sign.verify(
StrUtil.bytes(StrUtil.format("{}.{}", headerBase64, payloadBase64), charset), ByteUtil.toBytes(StrUtil.format("{}.{}", headerBase64, payloadBase64), charset),
Base64.decode(signBase64)); Base64.decode(signBase64));
} }

View File

@ -1,7 +1,8 @@
package cn.hutool.json.jwt.signers; package cn.hutool.json.jwt.signers;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.digest.HMac; import cn.hutool.crypto.digest.HMac;
import java.nio.charset.Charset; import java.nio.charset.Charset;
@ -58,8 +59,8 @@ public class HMacJWTSigner implements JWTSigner {
public boolean verify(final String headerBase64, final String payloadBase64, final String signBase64) { public boolean verify(final String headerBase64, final String payloadBase64, final String signBase64) {
final String sign = sign(headerBase64, payloadBase64); final String sign = sign(headerBase64, payloadBase64);
return hMac.verify( return hMac.verify(
StrUtil.bytes(sign, charset), ByteUtil.toBytes(sign, charset),
StrUtil.bytes(signBase64, charset)); ByteUtil.toBytes(signBase64, charset));
} }
@Override @Override

View File

@ -2,7 +2,7 @@ package cn.hutool.json.jwt;
import cn.hutool.core.date.DatePattern; import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.util.ByteUtil;
import cn.hutool.json.jwt.signers.AlgorithmUtil; import cn.hutool.json.jwt.signers.AlgorithmUtil;
import cn.hutool.json.jwt.signers.JWTSigner; import cn.hutool.json.jwt.signers.JWTSigner;
import cn.hutool.json.jwt.signers.JWTSignerUtil; import cn.hutool.json.jwt.signers.JWTSignerUtil;
@ -10,12 +10,7 @@ import lombok.Data;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import java.util.Arrays; import java.util.*;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JWTTest { public class JWTTest {
@ -96,7 +91,7 @@ public class JWTTest {
"eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbImFsbCJdLCJleHAiOjE2MjQwMDQ4MjIsInVzZXJJZCI6MSwiYXV0aG9yaXRpZXMiOlsiUk9MRV_op5LoibLkuozlj7ciLCJzeXNfbWVudV8xIiwiUk9MRV_op5LoibLkuIDlj7ciLCJzeXNfbWVudV8yIl0sImp0aSI6ImQ0YzVlYjgwLTA5ZTctNGU0ZC1hZTg3LTVkNGI5M2FhNmFiNiIsImNsaWVudF9pZCI6ImhhbmR5LXNob3AifQ." + "eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbImFsbCJdLCJleHAiOjE2MjQwMDQ4MjIsInVzZXJJZCI6MSwiYXV0aG9yaXRpZXMiOlsiUk9MRV_op5LoibLkuozlj7ciLCJzeXNfbWVudV8xIiwiUk9MRV_op5LoibLkuIDlj7ciLCJzeXNfbWVudV8yIl0sImp0aSI6ImQ0YzVlYjgwLTA5ZTctNGU0ZC1hZTg3LTVkNGI5M2FhNmFiNiIsImNsaWVudF9pZCI6ImhhbmR5LXNob3AifQ." +
"aixF1eKlAKS_k3ynFnStE7-IRGiD5YaqznvK2xEjBew"; "aixF1eKlAKS_k3ynFnStE7-IRGiD5YaqznvK2xEjBew";
final boolean verify = JWT.of(token).setKey(StrUtil.utf8Bytes("123456")).verify(); final boolean verify = JWT.of(token).setKey(ByteUtil.toUtf8Bytes("123456")).verify();
Assert.assertTrue(verify); Assert.assertTrue(verify);
} }

View File

@ -18,7 +18,7 @@ public class AioServerTest {
@Override @Override
public void accept(final AioSession session) { public void accept(final AioSession session) {
StaticLog.debug("【客户端】:{} 连接。", session.getRemoteAddress()); StaticLog.debug("【客户端】:{} 连接。", session.getRemoteAddress());
session.write(BufferUtil.createUtf8("=== Welcome to Hutool socket server. ===")); session.write(BufferUtil.ofUtf8("=== Welcome to Hutool socket server. ==="));
} }
@Override @Override
@ -32,7 +32,7 @@ public class AioServerTest {
.append("Content-Type: text/html; charset=UTF-8\r\n")// .append("Content-Type: text/html; charset=UTF-8\r\n")//
.append("\r\n") .append("\r\n")
.append("Hello Hutool socket");// .append("Hello Hutool socket");//
session.writeAndClose(BufferUtil.createUtf8(response)); session.writeAndClose(BufferUtil.ofUtf8(response));
}else { }else {
session.read(); session.read();
} }

View File

@ -34,8 +34,8 @@ public class NioClientTest {
}); });
client.listen(); client.listen();
client.write(BufferUtil.createUtf8("你好。\n")); client.write(BufferUtil.ofUtf8("你好。\n"));
client.write(BufferUtil.createUtf8("你好2。")); client.write(BufferUtil.ofUtf8("你好2。"));
// 在控制台向服务器端发送数据 // 在控制台向服务器端发送数据
Console.log("请输入发送的消息:"); Console.log("请输入发送的消息:");
@ -43,7 +43,7 @@ public class NioClientTest {
while (scanner.hasNextLine()) { while (scanner.hasNextLine()) {
final String request = scanner.nextLine(); final String request = scanner.nextLine();
if (request != null && request.trim().length() > 0) { if (request != null && request.trim().length() > 0) {
client.write(BufferUtil.createUtf8(request)); client.write(BufferUtil.ofUtf8(request));
} }
} }
} }

View File

@ -45,6 +45,6 @@ public class NioServerTest {
public static void doWrite(final SocketChannel channel, String response) throws IOException { public static void doWrite(final SocketChannel channel, String response) throws IOException {
response = "收到消息:" + response; response = "收到消息:" + response;
//将缓冲数据写入渠道返回给客户端 //将缓冲数据写入渠道返回给客户端
channel.write(BufferUtil.createUtf8(response)); channel.write(BufferUtil.ofUtf8(response));
} }
} }