diff --git a/hutool-core/src/main/java/cn/hutool/v7/core/text/StrUtil.java b/hutool-core/src/main/java/cn/hutool/v7/core/text/StrUtil.java index c76df0273..a510272bf 100644 --- a/hutool-core/src/main/java/cn/hutool/v7/core/text/StrUtil.java +++ b/hutool-core/src/main/java/cn/hutool/v7/core/text/StrUtil.java @@ -228,7 +228,7 @@ public class StrUtil extends CharSequenceUtil implements StrPool { if (null == charset) { charset = Charset.defaultCharset(); } - return charset.decode(data).toString(); + return charset.decode(data.duplicate()).toString(); } // endregion diff --git a/hutool-core/src/test/java/cn/hutool/v7/core/text/StrUtilTest.java b/hutool-core/src/test/java/cn/hutool/v7/core/text/StrUtilTest.java index a28a456d9..c48318df9 100644 --- a/hutool-core/src/test/java/cn/hutool/v7/core/text/StrUtilTest.java +++ b/hutool-core/src/test/java/cn/hutool/v7/core/text/StrUtilTest.java @@ -22,6 +22,8 @@ import cn.hutool.v7.core.util.RandomUtil; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -654,4 +656,21 @@ public class StrUtilTest { assertEquals("start12middle3end", concat); } + + @Test + public void testByteBufferSideEffect() { + final String originalText = "Hello"; + final ByteBuffer buffer = ByteBuffer.wrap(originalText.getBytes(StandardCharsets.UTF_8)); + // 此时 buffer.remaining() == 5 + assertEquals(5, buffer.remaining()); + + // 调用工具类转换,打印buffer内容 + final String result = StrUtil.str(buffer, StandardCharsets.UTF_8); + assertEquals(originalText, result); + + // 预期: + // 工具类不应该修改原 buffer 的指针,remaining 应该依然为 5 + // 再次调用工具类转换,输出结果应该不变 + assertEquals(originalText, StrUtil.str(buffer, StandardCharsets.UTF_8)); + } }