read byte data into a byte buffer and convert byte data into character data : CharSet « File « Java Tutorial






import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
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 BufferConverter {
  public static void main(String[] arguments) {
    try {
      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);
      for (int i = 0; source.remaining() > 0; i++)
        System.out.print(source.get() + " ");

      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; destination.remaining() > 0; i++)
        System.out.print(destination.get());
    } catch (Exception ioe) {
      System.out.println(ioe.getMessage());
    }
  }
}








11.57.CharSet
11.57.1.CharSet alias list
11.57.2.CharSet Lister
11.57.3.read byte data into a byte buffer and convert byte data into character data
11.57.4.Displays Available Charsets and aliases
11.57.5.Get the default charset