根据上一章节:java NIO(二) 缓冲区的介绍,我们给出实际使用的例子:
package com.z;
import java.nio.CharBuffer;
public class BufferFillPrint {
private static int index = 0;
private static String[] strings = {
"A ",
"CHANGCHENG ",
"A ",
"ZUGUO ",
"A ",
"A..."
};
private static boolean fill(CharBuffer buffer){
if(index == strings.length){
return false;
}
String string = strings[index++];
for(int i = 0; i < string.length(); i ++){
buffer.put(string.charAt(i));
}
return true;
}
private static void print(CharBuffer buffer){
while(buffer.hasRemaining()){
System.out.print(buffer.get());
}
}
public static void main(String[] args){
CharBuffer buffer = CharBuffer.allocate(100);
while(fill(buffer)){
buffer.flip();//先要flip()进行翻转,因为fill()后的position已经在最后
print(buffer);
buffer.clear();//打印后要clear(),因为pring()后的position已经在limit处
}
}
}