Java File Read via ByteBuffer readFile(String filePath)

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

Description

Read a file using nio

License

Apache License

Parameter

Parameter Description
filePath The path of the file to read

Exception

Parameter Description
IOException If it failed

Return

What it read in file (as a string)

Declaration

public static String readFile(String filePath) throws IOException 

Method Source Code

//package com.java2s;
/*//from   w w w .ja  v a2  s.co m
 * Copyright 2015 TheShark34
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

import java.io.IOException;

import java.io.RandomAccessFile;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

public class Main {
    /**
     * Read a file using nio
     * 
     * @param filePath
     *            The path of the file to read
     * @return What it read in file (as a string)
     * @throws IOException
     *             If it failed
     */
    public static String readFile(String filePath) throws IOException {
        String readString = "";
        RandomAccessFile file = new RandomAccessFile(filePath, "r");
        FileChannel channel = file.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (channel.read(buffer) > 0) {
            buffer.flip();
            for (int i = 0; i < buffer.limit(); i++)
                readString += (char) buffer.get();
            buffer.clear();
        }
        channel.close();
        file.close();
        return readString;
    }
}

Related

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