Java File Read via ByteBuffer readFile(File file)

Here you can find the source of readFile(File file)

Description

Read the file contents of the given file using the default character set.

License

Open Source License

Parameter

Parameter Description
file The file to read.

Exception

Parameter Description
IOException If the given file could not be read.

Return

A character buffer containing the file contents.

Declaration

private static CharBuffer readFile(File file) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class Main {
    /**/*ww w  .  j a  va  2s  .  com*/
     * Read the file contents of the given file
     * using the default character set.
     * 
     * @param file
     *          The file to read.
     * 
     * @return   A character buffer containing the file contents.
     * 
     * @throws   IOException
     *          If the given file could not be read.
     */
    private static CharBuffer readFile(File file) throws IOException {
        FileChannel channel = null;
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(file);
            channel = stream.getChannel();
            ByteBuffer byteBuffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
            CharBuffer charBuffer = Charset.defaultCharset().newDecoder().decode(byteBuffer);
            return charBuffer;
        } finally {
            if (stream != null)
                stream.close();
        }
    }
}

Related

  1. readEntireFile(java.io.File file)
  2. readerToString(Reader reader)
  3. readFC(String fname, int length)
  4. readFile(File file)
  5. readFile(File file)
  6. readFile(File file)
  7. readFile(File file)
  8. readFile(File file)
  9. readFile(File file)