Java File to Byte Array getBytes(File file)

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

Description

get Bytes

License

Open Source License

Declaration

public static byte[] getBytes(File file) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2016 Chen Chao(cnfree2000@hotmail.com).
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*from   w  w  w . j  a  v a2 s .co m*/
 *  Chen Chao  - initial API and implementation
 *******************************************************************************/

import java.io.BufferedInputStream;

import java.io.ByteArrayOutputStream;
import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

public class Main {
    public static byte[] getBytes(File file) {
        if (file == null || !file.exists())
            return null;
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
            byte[] tmp = new byte[4096];
            InputStream is = new BufferedInputStream(new FileInputStream(
                    file));
            while (true) {
                int r = is.read(tmp);
                if (r == -1)
                    break;
                out.write(tmp, 0, r);
            }
            byte[] bytes = out.toByteArray();
            is.close();
            out.close();
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

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