import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
/**
*
* convert text to and from ByteBuffer
*
*/
public class Buffer2Text {
private static final int BSIZE = 1024;
private static final String FILE_NAME = "d:\\a.txt";
public static void main(String[] args) throws Exception {
FileChannel fc = new FileOutputStream(FILE_NAME).getChannel();
fc.write(ByteBuffer.wrap("中国人".getBytes()));
fc.close();
fc = new FileInputStream(FILE_NAME).getChannel();
ByteBuffer bb = ByteBuffer.allocate(BSIZE);
fc.read(bb);
bb.flip();
//乱码
System.out.println(bb.asCharBuffer());
//使用系统默认字符集编码进行解码
bb.rewind();//指针返回到数据开始部分
String encoding = System.getProperty("file.encoding");
System.out.println("Decoded using " + encoding + ": " + Charset.forName(encoding).decode(bb));
fc.close();
//如果使用将要输出的字符集进行编码
fc = new FileOutputStream(FILE_NAME).getChannel();
fc.write(ByteBuffer.wrap("中国人".getBytes("UTF-16BE")));
fc.close();
//再输出的时候就OK
fc = new FileInputStream(FILE_NAME).getChannel();
bb.clear();
fc.read(bb);
bb.flip();
System.out.println("--: " + bb.asCharBuffer());
fc.close();
//使用CharBuffer来写
fc = new FileOutputStream(FILE_NAME).getChannel();
//这里的size将决定输出bb.asCharBuffer()的大小
//一个字符两个字节,多出的字节也会打印,如果分配的空间不够,则会抛出异常
bb = ByteBuffer.allocate(6);
bb.asCharBuffer().put("外国人");
fc.write(bb);
fc.close();
//读出
fc = new FileInputStream(FILE_NAME).getChannel();
bb.clear();
fc.read(bb);
bb.flip();
System.out.println("++: " + bb.asCharBuffer());
fc.close();
}
}
[java][nio]convert text to and from ByteBuffer
最新推荐文章于 2022-11-09 21:59:57 发布