[java][nio]convert text to and from ByteBuffer

本文通过示例展示了如何使用 Java 的 NIO (New IO) API 进行文件操作,包括如何将字符串编码为字节并写入文件、从文件中读取字节并解码为字符串的过程,并特别关注了字符集编码问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



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();
}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值