Java File Read via ByteBuffer readNIOFile(String filePath)

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

Description

read NIO File

License

Open Source License

Declaration

public static List<String> readNIOFile(String filePath) throws Exception 

Method Source Code

//package com.java2s;
/** Copyright (C) 2015 //from w  w w  . j  a  v a  2 s.  c o  m
 * @author Mitra Ansariola 
 * 
 * This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
Contact info:  megrawm@science.oregonstate.edu
    
 */

import java.io.RandomAccessFile;

import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

import java.util.ArrayList;

import java.util.List;

public class Main {
    public static List<String> readNIOFile(String filePath) throws Exception {
        List<String> lineList = new ArrayList<String>();
        RandomAccessFile aFile = new RandomAccessFile(filePath, "r");
        FileChannel inChannel = aFile.getChannel();
        MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
        buffer.load();
        char c = '0';
        StringBuffer lineStr = new StringBuffer();
        for (int i = 0; i < buffer.limit(); i++) {
            while ((c = (char) buffer.get()) != '\n') {
                lineStr.append(c);
                i++;
            }
            lineList.add(lineStr.toString());
            lineStr.setLength(0);
        }
        buffer.clear(); // do something with the data and clear/compact it.
        inChannel.close();
        aFile.close();
        return lineList;
    }
}

Related

  1. readLong(InputStream is)
  2. readLong(InputStream is, ByteOrder bo)
  3. readLong(RandomAccessFile raFile)
  4. readLTriad(byte[] triad)
  5. readNByte(ReadableByteChannel channel, int n)
  6. readShort(byte[] bytes, int start)
  7. readShort(DataInput input)
  8. readShortBuffer(DataInputStream input)
  9. readShortByteArray(DataInput in)