Java FileInputStream Read readFile(File file)

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

Description

Read the given file, returning a byte[] of its contents.

License

Open Source License

Parameter

Parameter Description
file non-null; the file to read

Return

non-null; its contents

Declaration

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

Method Source Code

//package com.java2s;
// the rights to use, copy, modify, merge, publish, distribute, sublicense,

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

public class Main {
    /**/*from ww  w .  ja v a2 s  . co  m*/
     * Read the given file, returning a <code>byte[]</code> of its contents.
     * The file should already be known to exist, be readable, and be a regular
     * file (not a directory or special file).
     *
     * @param file non-null; the file to read
     * @return non-null; its contents 
     */
    static public byte[] readFile(File file) throws IOException {
        if (file == null) {
            throw new NullPointerException("file == null");
        }

        long length = file.length();
        int len = (int) length;

        if (length != len) {
            // probably won't ever happen
            throw new RuntimeException("File too long: " + file);
        }

        byte[] buf = new byte[len];
        FileInputStream fis = new FileInputStream(file);

        int at = 0;
        while (at < len) {
            int amt = fis.read(buf, at, len - at);
            if (amt == -1) {
                throw new RuntimeException("Unexpected EOF at " + at + " in file: " + file);
            }
            at += amt;
        }

        return buf;
    }
}

Related

  1. readFile(File file)
  2. readFile(File file)
  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(File file)