Java File Read via ByteBuffer readFileIntoString(String path)

Here you can find the source of readFileIntoString(String path)

Description

Read the contents of a file into String.

License

LGPL

Parameter

Parameter Description
path the path

Exception

Parameter Description
IOException Signals that an I/O exception has occurred.

Return

the string

Declaration

public static String readFileIntoString(String path) throws IOException 

Method Source Code


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

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class Main {
    /**// w  ww . j  a  v a2 s.c  om
     * Read the contents of a file into String.
     *
     * @param path the path
     * @return the string
     * @throws IOException Signals that an I/O exception has occurred.
     */
    public static String readFileIntoString(String path) throws IOException {
        FileInputStream stream = new FileInputStream(new File(path));
        try {
            FileChannel fileChannel = stream.getChannel();
            MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0,
                    fileChannel.size());
            return Charset.defaultCharset().decode(mappedByteBuffer).toString();
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }
}

Related

  1. readFileChannelFully(FileChannel fileChannel, byte buf[], int off, int len)
  2. readFileDataIntoBufferBE(FileChannel fc, final int size)
  3. readFileFragment(FileChannel fc, long pos, int size)
  4. readFileHeader(FileInputStream fpi)
  5. readFileIntoString(File localFile)
  6. readFileNIO(String path, StringBuilder builder)
  7. readFileToBuffer(java.io.File file)
  8. readFileToString(String path)
  9. readFileToString(String path)