Java File Read via ByteBuffer readFile(String path)

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

Description

Read file.

License

Apache License

Parameter

Parameter Description
path the path

Return

the string

Declaration

public static String readFile(String path) 

Method Source Code


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

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

public class Main {
    /**/*from w  ww .jav a 2  s  .c  o  m*/
     * Read file.
     *
     * @param path the path
     * @return the string
     */
    public static String readFile(String path) {
        try {
            FileInputStream stream = null;
            try {
                stream = new FileInputStream(new File(path));
                FileChannel fc = stream.getChannel();
                MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
                /* Instead of using default, pass in a decoder. */
                return Charset.defaultCharset().decode(bb).toString();
            } catch (FileNotFoundException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            } finally {
                stream.close();
            }
        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
        return "";
    }
}

Related

  1. readFile(String filename)
  2. readFile(String filePath)
  3. readFile(String name)
  4. readFile(String name)
  5. readFile(String path)
  6. readFile(String path)
  7. readFile(String path)
  8. readFileAsByteArray(File file)
  9. readFileAsByteArray(String path)