Flyingis

Talking and thinking freely !
Flying in the world of GIS !
随笔 - 156, 文章 - 16, 评论 - 589, 引用 - 0
数据加载中……

Java I/O中的数据编码转换

作者:Flyingis

      JDK1.4
开始便引入了java.nio.*包,其目的在于提高I/O的速度,这是因为该类库使用的结构更接近于操作系统执行I/O的方式,即通过通道和缓冲器来读写数据。在实际应用中,和我们直接交互的是缓冲器,然后把缓冲器派送到通道,通道要么从缓冲器获得数据,要么向缓冲器发送数据。


    在基于
Java的各种开发中,字符编码是常见的问题之一,在最基本的Java I/O中也存在这种问题。新的Java I/O通过通道和缓冲器来读写数据,缓冲器容纳的是普通的字节,为了把它们转换成字符,我们要么在输入的时候对其进行编码,要么在从缓冲器输出时对它们进行解码。


import java.io.*;

import java.nio.*;

import java.nio.channels.*;

import java.nio.charset.*;

public class ByteToCharacter {

  private static final int SIZE = 1024;

  public static void main(String[] args) throws Exception {

FileChannel fc = new FileOutputStream(“Output.txt”).getChannel();

ByteBuffer buffer = ByteBuffer.allocate(SIZE);

/**

* 在输入的时候进行编码方式一

*/

fc.write(ByteBuffer.wrap(“Good holiday!”.getBytes(“UTF-16BE”)));  // UTF-16BE可以更换为其他编码方式

fc.close();

fc = new FileInputStream(“Output.txt”).getChannel();

fc.read(buffer);

buffer.flip();  //准备从缓冲区读取已经写入的数据

System.out.println(buffer.asCharBuffer());

/**

* 在输入的时候进行编码方式二

* 通过asCharBuffer()方法直接以char形式将字符写入

*/

fc = new FileOutputStream(“Output.txt”).getChannel();

buffer.clear();

buffer.asCharBuffer.put(“Good holiday has passed!”);

fc.write(buffer);

fc.close();

fc = new FileInputStream(“Output.txt”).getChannel();

buffer.clear();

fc.read(buffer);

buffer.flip();

System.out.println(buffer.asCharBuffer());

/**

* 从缓冲器输出时进行编码

*/

fc = new FileOutputStream(“Output.txt”).getChannel();

fc.write(ByteBuffer.wrap(“Once again!”.getBytes()));

fc.close();

fc = new FileInputStream(“Output.txt”).getChannel();

buffer.clear();

fc.read(buffer);

buffer.flip();

String encode = System.getProperty(“file.encoding”);  // 平台缺省字符集,更加通用的方法,跨平台特性的体现之一

System.out.println(Charset.forName(encode).decode(buffer));

}

}


   
在上述代码中,如果不对从缓冲器写入的数据进行正确编码,那么当再次通过缓冲器读取这些数据时,将不能显示任何所需要的数据。


    JDK
中的java.nio.charset.Charset类提供了把数据编码成多种不同类型的字符集的工具,满足在各种应用中的编码需求。

posted on 2006-01-03 14:02 Flyingis 阅读(1418) 评论(0)  编辑  收藏 所属分类: JavaSE


只有注册用户登录后才能发表评论。


网站导航: