Java File to Byte Array getBytesFromFile(File file)

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

Description

get Bytes From File

License

Open Source License

Declaration

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

Method Source Code


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

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    private static final String EMPTY = "";

    public static byte[] getBytesFromFile(File file) throws IOException {

        InputStream is = new FileInputStream(file);

        long length = file.length();

        if (length > Integer.MAX_VALUE) {
            is.close();//from ww  w  .  ja  va  2s  . c  o  m
            throw new IOException("File is to large " + file.getName());
        }

        byte[] bytes = new byte[(int) length];

        int offset = 0;
        int numRead = 0;

        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

        if (offset < bytes.length) {
            is.close();
            throw new IOException("Could not completely read file " + file.getName());
        }

        is.close();

        return bytes;
    }

    public static String getName(String filePath) {
        if (filePath == null || filePath.length() == 0) {
            return EMPTY;
        }

        int i = filePath.lastIndexOf("/");
        int j = filePath.lastIndexOf(".");

        if (i != -1) {
            if (j > i) {
                return filePath.substring(i + 1, j);
            } else if (i != filePath.length() - 1) {
                return filePath.substring(i + 1);
            }
        } else {
            if (j > 0) {
                return filePath.substring(0, j);
            } else if (j == 0) {
                return EMPTY;
            }
        }

        return filePath;
    }
}

Related

  1. getBytesFromFile(File file)
  2. getBytesFromFile(File file)
  3. getBytesFromFile(File file)
  4. getBytesFromFile(File file)
  5. getBytesFromFile(File file)
  6. getBytesFromFile(File file)
  7. getBytesFromFile(File file)
  8. getBytesFromFile(File file)
  9. getBytesFromFile(File file)