From 28f267c5a7111c430de1e0b3c31e751c4a8a15e9 Mon Sep 17 00:00:00 2001 From: Looly Date: Tue, 25 Nov 2025 18:53:38 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8DStrUtil.str(ByteBuffer,=20Cha?= =?UTF-8?q?rset)=20=E6=96=B9=E6=B3=95=E4=BF=AE=E6=94=B9=E5=85=A5=E5=8F=82?= =?UTF-8?q?=20ByteBuffer=20=E7=9A=84=20position=EF=BC=8C=E5=AF=BC=E8=87=B4?= =?UTF-8?q?=E5=85=A5=E5=8F=82=E5=8F=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/cn/hutool/v7/core/text/StrUtil.java | 2 +- .../cn/hutool/v7/core/text/StrUtilTest.java | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) 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)); + } }