Here you can find the source of readContentsNIO(FileInputStream input, String encoding, boolean decodeNIO)
public static String readContentsNIO(FileInputStream input, String encoding, boolean decodeNIO) throws IOException
//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(); } }