修复StrUtil.str(ByteBuffer, Charset) 方法修改入参 ByteBuffer 的 position,导致入参变化

This commit is contained in:
Will 2025-11-25 18:08:03 +08:00
parent 17f78f8cd4
commit a6151b6ee8
2 changed files with 19 additions and 1 deletions

View File

@ -261,7 +261,7 @@ public class StrUtil extends CharSequenceUtil implements StrPool {
if (null == charset) { if (null == charset) {
charset = Charset.defaultCharset(); charset = Charset.defaultCharset();
} }
return charset.decode(data).toString(); return charset.decode(data.duplicate()).toString();
} }
/** /**

View File

@ -1,6 +1,7 @@
package cn.hutool.core.io; package cn.hutool.core.io;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -63,4 +64,21 @@ public class BufferUtilTest {
// 读取剩余部分 // 读取剩余部分
assertEquals("cc", StrUtil.utf8Str(BufferUtil.readBytes(buffer))); assertEquals("cc", StrUtil.utf8Str(BufferUtil.readBytes(buffer)));
} }
@Test
public void testByteBufferSideEffect() {
String originalText = "Hello";
ByteBuffer buffer = ByteBuffer.wrap(originalText.getBytes(StandardCharsets.UTF_8));
// 此时 buffer.remaining() == 5
assertEquals(5, buffer.remaining());
// 调用工具类转换打印buffer内容
String result = StrUtil.str(buffer, StandardCharsets.UTF_8);
assertEquals(originalText, result);
// 预期
// 工具类不应该修改原 buffer 的指针remaining 应该依然为 5
// 再次调用工具类转换输出结果应该不变
assertEquals(originalText, StrUtil.str(buffer, StandardCharsets.UTF_8));
}
} }