1. 程式人生 > >NIO初學,以及java.nio.charset.MalformedInputException: Input length = 1

NIO初學,以及java.nio.charset.MalformedInputException: Input length = 1

import java.io.*;
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.util.Queue;

/**
 * NIO初學
 */
public class FirstNio {
    public static void main(String[] args) {
        File file=    new File("E:\\IDEAproject\\measurement\\src\\test\\java\\Find.java");
        try {
            //建立FileInputStream,以該檔案輸入流建立  FileChannel
            FileChannel inChannel= new FileInputStream(file).getChannel();


            //以檔案輸入流建立FileChannel,用以控制輸出
            FileChannel outChannel=  new FileOutputStream("a.text").getChannel();
            //將FileChannel裡面的全部資料對映成ByteBuffer
           MappedByteBuffer buffer= inChannel.map(FileChannel.MapMode.READ_ONLY,0,file.length());

           //使用GBK的字符集來建立解碼器,
            Charset charset=  Charset.forName("GBK");//如果亂碼就改用utf-8

            //直接將buffer裡的資料全部輸出
            outChannel.write(buffer);
            //再次呼叫buffer的clear()方法,復原limit,position的位置
            buffer.clear();
            //建立解碼器(CharsetDecoder)物件
         CharsetDecoder charsetDecoder= charset.newDecoder();
         //使用解碼器將ByteBuffer轉換成CharBuffer
           CharBuffer charBuffer= charsetDecoder.decode(buffer);
          /* 如果報錯(***java.nio.charset.MalformedInputException: Input length = 1***)
            就把CharBuffer charBuffer= charsetDecoder.decode(buffer);註釋,用下面這個CharBuffer charBuffer= charset.decode(buffer);
         */
          // CharBuffer charBuffer= charset.decode(buffer);
        //CharBuffer 的toString方法可以獲得對應的字串
            System.out.println(charBuffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}