集册 Java实例教程 使用文件通道将字节数据读入字节缓冲区并将字节数据转换为字符数据

使用文件通道将字节数据读入字节缓冲区并将字节数据转换为字符数据

欢马劈雪     最近更新时间:2020-01-02 10:19:05

415
使用文件通道将字节数据读入字节缓冲区并将字节数据转换为字符数据

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;
/**
 * 时 代 J a v a - N o w J a v a . c o m 提 供 
**/

import java.nio.ByteBuffer;

import java.nio.CharBuffer;

import java.nio.channels.FileChannel;

import java.nio.charset.Charset;

import java.nio.charset.CharsetDecoder;


public class Main {

  public static void main(String[] arguments) {

    try {

      // read byte data into a byte buffer
      /*
      时 代 J a v a 公 众 号 - nowjava.com 提 供
      */

      String data = "friends.dat";

      FileInputStream inData = new FileInputStream(data);

      FileChannel inChannel = inData.getChannel();

      long inSize = inChannel.size();

      ByteBuffer source = ByteBuffer.allocate((int) inSize);

      inChannel.read(source, 0);

      source.position(0);

      System.out.println("Original byte data:");

      for (int i = 0; source.remaining() > 0; i++) {

        System.out.print(source.get() + " ");

      }

      // convert byte data into character data

      source.position(0);

      Charset ascii = Charset.forName("US-ASCII");

      CharsetDecoder toAscii = ascii.newDecoder();

      CharBuffer destination = toAscii.decode(source);

      destination.position(0);

      System.out.println("\n\nNew character data:");

      for (int i = 0
展开阅读全文