Java File to Byte Array getBytes(File f)

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

Description

get Bytes

License

Open Source License

Declaration

public static byte[] getBytes(File f) throws IOException 

Method Source Code

//package com.java2s;
/*//from ww  w  . ja va 2s  .  c om
 * Spirit, a study/biosample management tool for research.
 * Copyright (C) 2018 Idorsia Pharmaceuticals Ltd., Hegenheimermattweg 91,
 * CH-4123 Allschwil, Switzerland.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 * @author Joel Freyss
 */

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;

import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

public class Main {
    public static byte[] getBytes(File f) throws IOException {
        FileInputStream is = new FileInputStream(f);
        byte[] res = new byte[(int) f.length()];
        is.read(res);
        is.close();
        return res;
    }

    public static byte[] getBytes(InputStream is) throws IOException {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            redirect(is, os);
            return os.toByteArray();
        }
    }

    public static void redirect(byte[] bytes, OutputStream os) throws IOException {
        try (ByteArrayInputStream is = new ByteArrayInputStream(bytes)) {
            redirect(is, os);
        }
    }

    public static void redirect(InputStream is, OutputStream os) throws IOException {
        byte[] buf = new byte[512];
        int c;
        while ((c = is.read(buf)) > 0) {
            os.write(buf, 0, c);
        }
    }

    public static void redirect(Reader is, Writer os) throws IOException {
        char[] buf = new char[512];
        int c;
        while ((c = is.read(buf)) > 0) {
            os.write(buf, 0, c);
        }
    }
}

Related

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