Initial commit
This commit is contained in:
65
Homework0520/src/BufferFlipCompact.java
Normal file
65
Homework0520/src/BufferFlipCompact.java
Normal file
@@ -0,0 +1,65 @@
|
||||
import java.nio.CharBuffer;
|
||||
|
||||
public class BufferFlipCompact {
|
||||
public static void main(String[] args) {
|
||||
// 创建一个容量为8的CharBuffer
|
||||
CharBuffer buffer = CharBuffer.allocate(8);
|
||||
System.out.println("初始状态:");
|
||||
printBufferStatus(buffer);
|
||||
|
||||
// 写入字符串"Hello"
|
||||
buffer.put("Hello");
|
||||
System.out.println("\n写入'Hello'后:");
|
||||
printBufferStatus(buffer);
|
||||
|
||||
// 翻转缓冲区准备读取
|
||||
buffer.flip();
|
||||
System.out.println("\n翻转缓冲区后(flip):");
|
||||
printBufferStatus(buffer);
|
||||
|
||||
// 读取前3个字符('H', 'e', 'l')
|
||||
System.out.println("\n读取前3个字符:");
|
||||
for (int i = 0; i < 3; i++) {
|
||||
char c = buffer.get();
|
||||
System.out.print(c + " ");
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
System.out.println("\n读取3个字符后:");
|
||||
printBufferStatus(buffer);
|
||||
|
||||
// 压缩缓冲区
|
||||
buffer.compact();
|
||||
System.out.println("\n压缩缓冲区后(compact):");
|
||||
printBufferStatus(buffer);
|
||||
|
||||
// 再写入"World"
|
||||
buffer.put("World");
|
||||
System.out.println("\n写入'World'后:");
|
||||
printBufferStatus(buffer);
|
||||
|
||||
// 翻转并打印最终缓冲区内容
|
||||
buffer.flip();
|
||||
System.out.println("\n最终缓冲区内容:");
|
||||
while (buffer.hasRemaining()) {
|
||||
System.out.print(buffer.get());
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
// 显示完整的缓冲区内容(包括未读取的部分)
|
||||
buffer.rewind(); // 回到开始位置
|
||||
System.out.println("\n完整缓冲区内容:");
|
||||
while (buffer.hasRemaining()) {
|
||||
System.out.print(buffer.get());
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
// 打印缓冲区状态
|
||||
private static void printBufferStatus(CharBuffer buffer) {
|
||||
System.out.println("Position: " + buffer.position() +
|
||||
", Limit: " + buffer.limit() +
|
||||
", Capacity: " + buffer.capacity() +
|
||||
", Remaining: " + buffer.remaining());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user