美文网首页
16.RandomAccessFile,字符集编码和解码

16.RandomAccessFile,字符集编码和解码

作者: 未知的证明 | 来源:发表于2019-03-08 23:24 被阅读0次

RandomAccessFile

Instances of this class support both reading and writing to a random access file. A random access file behaves like a large array of bytes stored in the file system. There is a kind of cursor, or index into the implied array, called the file pointer; input operations read bytes starting at the file pointer and advance the file pointer past the bytes read. If the random access file is created in read/write mode, then output operations are also available; output operations write bytes starting at the file pointer and advance the file pointer past the bytes written.

package com.liyuanfeng.nio;

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 NioTest13 {
    public static void main(String[] args) throws Exception {


        String inpuFile = "NioTest13_In.txt";
        String outputFile = "NioTest13_Out.txt";

        RandomAccessFile inputRandomAccesssFile = new RandomAccessFile(inpuFile, "r");
        RandomAccessFile outputRandomAccesssFile = new RandomAccessFile(outputFile, "rw");
        long inputLength = new File(inpuFile).length();
        FileChannel inputFileChannel = inputRandomAccesssFile.getChannel();
        FileChannel outputFileChannel = outputRandomAccesssFile.getChannel();

        MappedByteBuffer inputData = inputFileChannel.map(FileChannel.MapMode.READ_ONLY, 0, inputLength);//Maps a region of this channel's file directly into memory.

        System.out.println("==============================");

        Charset.availableCharsets().forEach((k, v) -> System.out.println(k + "," + v));

        System.out.println("=============================");

        Charset charset = Charset.forName("utf-8");
        CharsetDecoder charsetDecoder = charset.newDecoder();
        CharsetEncoder charsetEncoder = charset.newEncoder();


        CharBuffer charBuffer = charsetDecoder.decode(inputData);//inputData为ByteBuffer
        ByteBuffer outputData = charsetEncoder.encode(charBuffer);
        outputFileChannel.write(outputData);

        inputRandomAccesssFile.close();
        outputRandomAccesssFile.close();


    }
}

相关文章

网友评论

      本文标题:16.RandomAccessFile,字符集编码和解码

      本文链接:https://www.haomeiwen.com/subject/tykjpqtx.html