Java File to Byte Array getBytesFromFile(String filename)

Here you can find the source of getBytesFromFile(String filename)

Description

returns byte array containing contents of file at specified path

License

Apache License

Declaration

public static byte[] getBytesFromFile(String filename) throws IOException 

Method Source Code


//package com.java2s;
/*//from ww  w .ja va  2s. c  om
 Copyright (C) 2012 The Stanford MobiSocial Laboratory
    
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
    
   http://www.apache.org/licenses/LICENSE-2.0
    
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

import java.io.*;

public class Main {
    /** returns byte array containing contents of file at specified path */
    public static byte[] getBytesFromFile(String filename) throws IOException {
        File f = new File(filename);
        long len = f.length();
        if (len >= (1L << 32))
            throw new RuntimeException("File " + filename + " is larger than 2^32 bytes: " + len);

        BufferedInputStream is = new BufferedInputStream(new FileInputStream(f));

        int int_len = (int) len;
        byte b[] = new byte[int_len];
        int totalBytesRead = 0;
        while (true) {
            int bytesToRead = int_len - totalBytesRead;
            int bytesRead = is.read(b, totalBytesRead, bytesToRead);
            if (bytesRead == 0)
                throw new RuntimeException("Unexpected end of file: " + filename);
            totalBytesRead += bytesRead;
            if (totalBytesRead == int_len)
                break;
        }

        // make sure we read all the bytes... check that the next byte returned is -1
        if (is.read() != -1)
            throw new RuntimeException("File " + filename + " has more than expected bytes: " + len);

        is.close();
        return b;
    }

    public static void close(Closeable resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                // Do your thing with the exception. Print it, log it or mail it.
                e.printStackTrace();
            }
        }
    }
}

Related

  1. getBytesFromFile(File inputFile)
  2. getBytesFromFile(final File file)
  3. getBytesFromFile(String file)
  4. getBytesFromFile(String filename)
  5. getBytesFromFile(String fileName)
  6. getBytesFromFile(String filename)
  7. getBytesFromFile(String filepath)
  8. getBytesFromFile(String filePath)
  9. toByteArray(File file)