Java 编码解码

Java中使用unicode编码,各操作系统有自己的默认编码,如果我们要将随机数写到文件中必须将其转化成某种编码格式的字符串,我们选择系统的默认 字符集,然后将其写入:private void gernate() {

		File file = new File(FILE_PATH);
		FileOutputStream fos = null;
		FileChannel channel = null;
		ByteBuffer byteBuffer = ByteBuffer.allocate(SIZE);
		String tem = null;
		byte[] bytes = null;
		long begin = System.currentTimeMillis();
		long end = 0;
		int num = 0;
		try {
			log.info("begin:" + begin);
			fos = new FileOutputStream(file);
			channel = fos.getChannel();
			Random random = new Random();
			for (int i = 0; i < MAX_NUM; i++) {
				num = random.nextInt(MAX_NUM);
				tem = String.valueOf(num);
				tem += i < MAX_NUM - 1 ? "中普朗克y" : "";
				bytes = tem.getBytes();
				if (byteBuffer.remaining() < bytes.length) {
					byteBuffer.flip();
					channel.write(byteBuffer);
					byteBuffer.clear();
				}
				byteBuffer.put(bytes);
			}
			byteBuffer.flip();
			channel.write(byteBuffer);
			fos.close();
			end = System.currentTimeMillis();
			log.info("end:" + end + ",use :" + (end - begin));

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

这里需要注意的是String.getBytes()方法,将unicode字符转化成系统的默认字符序列。

对于写入的文件解码问题:我们使用CharsetDecoder,完全相反的操作,解码器在其中保存一定的状态,对于解码会返回结果状态:

public void count() {
		File file = new File(FILE_PATH);
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			FileChannel channel = fis.getChannel();
			ByteBuffer byteBuffer = ByteBuffer.allocate(5);
			CharBuffer charBuffer=CharBuffer.allocate(57);
			Charset charset=Charset.defaultCharset();
			CharsetDecoder decoder = charset.newDecoder();
			CoderResult decodeResult=CoderResult.OVERFLOW;
			while(channel.read(byteBuffer)!=-1){
				byteBuffer.flip();
				while(decodeResult==CoderResult.OVERFLOW){
					 decodeResult = decoder.decode(byteBuffer, charBuffer, false);
					 System.out.println(decodeResult);
					charBuffer.flip();
					System.out.print(charBuffer.toString());
					charBuffer.clear();
				}
				if(decodeResult==CoderResult.UNDERFLOW){
					byteBuffer.compact();
					decodeResult=CoderResult.OVERFLOW;
				}
			}
			
			System.out.println();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值