Translate Charset : Charset « I18N « Java Tutorial






import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

public class Main {
  static public void main(String args[]) throws Exception {
    File infile = new File("inFilename");
    File outfile = new File("outFilename");

    RandomAccessFile inraf = new RandomAccessFile(infile, "r");
    RandomAccessFile outraf = new RandomAccessFile(outfile, "rw");

    FileChannel finc = inraf.getChannel();
    FileChannel foutc = outraf.getChannel();

    MappedByteBuffer inmbb = finc.map(FileChannel.MapMode.READ_ONLY, 0, (int) infile.length());

    Charset inCharset = Charset.forName("UTF8");
    Charset outCharset = Charset.forName("UTF16");

    CharsetDecoder inDecoder = inCharset.newDecoder();
    CharsetEncoder outEncoder = outCharset.newEncoder();

    CharBuffer cb = inDecoder.decode(inmbb);
    ByteBuffer outbb = outEncoder.encode(cb);

    foutc.write(outbb);

    inraf.close();
    outraf.close();
  }
}








13.20.Charset
13.20.1.Listing All Available Unicode to Character Set Converters
13.20.2.Converting Between Strings (Unicode) and Other Character Set Encodings
13.20.3.encoder and decoder use a supplied ByteBuffer
13.20.4.Detect non-ASCII characters in string
13.20.5.List Charsets
13.20.6.Translate Charset
13.20.7.extends Charset to create Hex Charset