Java File Read via ByteBuffer readFile(File file)

Here you can find the source of readFile(File file)

Description

read File

License

Apache License

Declaration

public static byte[] readFile(File file) throws IOException 

Method Source Code


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

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
    public static byte[] readFile(File file) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream(4096);
        BufferedInputStream input = null;
        try {//w w  w.  ja v  a  2s . co m
            input = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[2048];
            for (;;) {
                int len = input.read(buffer);
                if (len == (-1))
                    break;
                output.write(buffer, 0, len);
            }
        } finally {
            if (input != null)
                close(input);
        }
        return output.toByteArray();
    }

    public static void readFile(File file, OutputStream output) throws IOException {
        FileInputStream input = null;
        FileChannel fc = null;
        try {
            input = new FileInputStream(file);
            fc = input.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(4096);
            for (;;) {
                buffer.clear();
                int n = fc.read(buffer);
                if (n == (-1))
                    break;
                output.write(buffer.array(), 0, buffer.position());
            }
            output.flush();
        } finally {
            if (fc != null)
                close(fc);
            if (input != null)
                close(input);
        }
    }

    private static void close(InputStream input) {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
    }

    private static void close(OutputStream output) {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
            }
        }
    }

    private static void close(FileChannel channel) {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException e) {
            }
        }
    }
}

Related

  1. readerToString(Reader reader)
  2. readFC(String fname, int length)
  3. readFile(File file)
  4. readFile(File file)
  5. readFile(File file)
  6. readFile(File file)
  7. readFile(File file)
  8. readFile(File file)
  9. readFile(java.io.File file)