Java File Read via ByteBuffer readFile(String path)

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

Description

read File

License

Apache License

Declaration

public static String readFile(String path) throws IOException 

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 {
    public static String readFile(String path) throws IOException {
        return readFile(new File(path));
    }//from  w ww.  j  a  v a 2s.c om

    public static String readFile(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        try {
            FileChannel fc = fis.getChannel();
            MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
            return Charset.defaultCharset().decode(bb).toString();
        } finally {
            SafeClose(fis);
        }
    }

    public static void SafeClose(Closeable is) {
        if (is == null)
            return;

        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Related

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