Java File to Byte Array fileToByteArray(String path)

Here you can find the source of fileToByteArray(String path)

Description

Returns the file at the specified path as a byte array.

License

Open Source License

Parameter

Parameter Description
path a parameter

Declaration

public static byte[] fileToByteArray(String path) 

Method Source Code

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

import java.io.*;

public class Main {
    /**/*from ww  w  .  ja  v a2  s . com*/
     * Returns the file at the specified path as a byte array.
     * @param path
     * @return
     */
    public static byte[] fileToByteArray(String path) {
        File file = new File(path);
        if (!file.exists() || file.isDirectory()) {
            return null;
        }
        FileInputStream in = null;
        try {
            byte[] array = new byte[(int) file.length()];
            in = new FileInputStream(file);
            in.read(array);
            return array;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * Returns whether or not the specified path is a directory.
     * @param path  the file path
     * @return  <i>true</i> if path is directory
     */
    public static boolean isDirectory(String path) {
        return new File(path).isDirectory();
    }
}

Related

  1. fileToByteArray(File file)
  2. fileToByteArray(final File f)
  3. fileToByteArray(final IFile file)
  4. fileToByteArray(String filePath)
  5. fileToByteArray(String fname)
  6. fileToBytes(File file)
  7. fileToBytes(File file)
  8. fileToBytes(File path)
  9. fileToBytes(File source)