数据转换

本文探讨了Java NIOCharset类中不同的数据编码种类,包括Big5、EUC-JP、GBK等,并展示了如何进行数据转换,如使用ByteBuffer和CharBuffer。同时,还列举了多种特殊字符集,如IBM系列编码,以及常见的UTF-8、UTF-16等。
摘要由CSDN通过智能技术生成

数据转换

  • java.nio.charset.Charset
    String encoding = System.getProperty(“file.encoding”); // 发现默认字符集,产生代表字符集名称的字符串
    System.out.println(Charset.forName(encoding).decode(buffer));

  • 对数组编码再写
    ByteBuffer.wrap(“Some text”.getBytes(“UTF-16BE”))

  • char类型转换器
    buffer.asCharBuffer().put(“Some text”);

package com.zachary.io.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

/**
 * @author Zachary.Zheng
 * @version 1.0
 * @date 2020年5月30日 下午6:40:55
 */
public class BufferToText {
   
	private static final int BSIZE = 1024;
	public static void main(String[] args) throws IOException {
   
		FileChannel fc = new FileOutputStream("file/output/nio/data2.txt").getChannel();
		fc.write(ByteBuffer.wrap("Some text".getBytes()));
		fc.close();
		
		fc = new FileInputStream("file/output/nio/data2.txt").getChannel();
		ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
		fc.read(buffer);
		buffer.flip();
		System.out.println(buffer.asCharBuffer()); // 存入时按字节,取出时按char,导致出现乱码
		// 解决乱码 方案1
		String encoding = System.getProperty("file.encoding"); // 发现默认字符集,产生代表字符集名称的字符串
		System.out.println(Charset.forName(encoding).decode(buffer));
		
		
		// 解决乱码 方案2
		fc = new FileOutputStream("file/output/nio/data2.txt").getChannel()</
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值