Java File Read via ByteBuffer readFile(String fileName)

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

Description

read File

License

Open Source License

Declaration

public static ByteBuffer readFile(String fileName) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
    public static ByteBuffer readFile(String fileName) {
        ByteBuffer buf = null;//from  ww w .ja  v a 2 s .c om
        FileChannel fc = null;
        try {
            FileInputStream fis = new FileInputStream(fileName);
            fc = fis.getChannel();
            int size = (int) fc.size();
            buf = readFileFragment(fc, 0, size);
        } catch (FileNotFoundException ex) {
            System.err.printf("File `%s' not found!\n", fileName);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (fc != null)
                    fc.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return buf;
    }

    public static ByteBuffer readFileFragment(FileChannel fc, long pos, int size) {
        ByteBuffer fragment = null;
        try {
            fc.position(pos);
            fragment = ByteBuffer.allocate(size);
            if (fc.read(fragment) != size)
                return null;
            fragment.rewind();
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return fragment;
    }
}

Related

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