Java File Read via ByteBuffer readContentsNIO(FileInputStream input, String encoding, boolean decodeNIO)

Here you can find the source of readContentsNIO(FileInputStream input, String encoding, boolean decodeNIO)

Description

read Contents NIO

License

Apache License

Declaration

public static String readContentsNIO(FileInputStream input, String encoding, boolean decodeNIO)
            throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;

public class Main {
    public static String readContentsNIO(FileInputStream input, String encoding, boolean decodeNIO)
            throws IOException {
        ByteBuffer bbuf;//from ww  w. ja va 2 s .  co  m

        FileChannel fc = input.getChannel();
        bbuf = ByteBuffer.allocate((int) fc.size());

        fc.read(bbuf);
        bbuf.flip();

        return decodeNIO ? decodeNIO(encoding, bbuf) : decodeIO(encoding, bbuf);
    }

    private static String decodeNIO(String encoding, ByteBuffer bbuf) {
        Charset cset = Charset.forName(encoding);
        CharsetDecoder csetdecoder = cset.newDecoder();

        csetdecoder.onMalformedInput(CodingErrorAction.REPLACE);
        csetdecoder.onUnmappableCharacter(CodingErrorAction.REPLACE);

        try {
            CharBuffer cbuf = csetdecoder.decode(bbuf);

            return cbuf.toString();
        } catch (CharacterCodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String decodeIO(String encoding, ByteBuffer bbuf) throws UnsupportedEncodingException {
        if (bbuf.hasArray())
            return new String(bbuf.array(), encoding);

        throw new IllegalArgumentException();
    }
}

Related

  1. readBytes(ReadableByteChannel channel, byte[] array)
  2. readBytes(String file)
  3. readCode(byte[] message)
  4. readColumnarKeyBlockDataForNoDictionaryCols(byte[] columnarKeyBlockData)
  5. readContent(File file)
  6. readData(String fileName, int size)
  7. readDelimitedFromInputStream(InputStream inputStream)
  8. readDouble(BufferedReader br, double[] buf)
  9. readDouble(byte[] src, int pointer)