Here you can find the source of readFileBytes(final File file)
Parameter | Description |
---|---|
file | the file object |
public static byte[] readFileBytes(final File file)
//package com.java2s; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Main { /**//from w w w . j a v a2 s.co m * Reads an array of bytes from the given input stream. * @param inputstream the input stream * @return the bytes or null if the inputstream is null */ public static byte[] readFileBytes(final InputStream inputstream) { if (inputstream == null) return null; // Start with a buffer size between 1K and 1M based on available memory. final int minBufferSize = (int) Math.max(1024, Math.min(Runtime.getRuntime().freeMemory() / 10, 1024 * 1024)); List buffers = new ArrayList(); int totalBytesRead = 0; // Fill buffer lists try { byte[] curBuf = new byte[minBufferSize]; int curBufPos = 0; int bytesRead; while ((bytesRead = inputstream.read(curBuf, curBufPos, curBuf.length - curBufPos)) != -1) { totalBytesRead += bytesRead; curBufPos += bytesRead; if (curBufPos == curBuf.length) { buffers.add(curBuf); curBuf = new byte[minBufferSize]; curBufPos = 0; } } buffers.add(curBuf); } catch (IOException ex) { // LOG.throwing("FileUtils", "readFileBytes", ex); throw new RuntimeException("Unable to read file bytes", ex); } byte[] result = new byte[totalBytesRead]; int pos = 0; Iterator it = buffers.iterator(); while (it.hasNext()) { byte[] curBuf = (byte[]) it.next(); int copy = curBuf.length; if (copy > (totalBytesRead - pos)) copy = totalBytesRead - pos; System.arraycopy(curBuf, 0, result, pos, copy); pos += copy; } return result; } /** * Reads the bytes from the given file if it is a file and it exists. * @param file the file object * @return a byte array */ public static byte[] readFileBytes(final File file) { byte[] data = null; if (file != null && file.exists() && file.isFile()) { RandomAccessFile raf = null; try { raf = new RandomAccessFile(file, "r"); data = new byte[(int) raf.length()]; raf.readFully(data); } catch (IOException ex) { ex.printStackTrace(); } finally { if (raf != null) { try { raf.close(); } catch (Exception ex) { // LOG.throwing("FileUtils", "readFileBytes", ex); } } } } return data; } }