Java File to Byte Array fileToByteArray(String filePath)

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

Description

Method for converting a file (represented by its path) in an array of bytes

License

Open Source License

Parameter

Parameter Description
filePath path of the file

Return

Result of the conversion

Declaration

public static byte[] fileToByteArray(String filePath) 

Method Source Code


//package com.java2s;

import java.io.*;

public class Main {
    private static final String ERROR_MESSAGE = "Error - this function is not supported in .Net";
    private static final boolean COMPILE_FOR_JAVA = true;

    /**/*from w  w  w.  j a  v  a2  s. c o m*/
     * Method for converting a file (represented by its path) in
     * an array of bytes
     * @param filePath path of the file
     * @return Result of the conversion
     * @since JSockets 1.0.0
     */
    public static byte[] fileToByteArray(String filePath) {
        if (COMPILE_FOR_JAVA) {
            File file = new File(filePath);
            byte[] bytes = null;

            try {
                FileInputStream fis = new FileInputStream(file);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];

                try {
                    for (int readNum; (readNum = fis.read(buf)) != -1;)
                        bos.write(buf, 0, readNum);
                } catch (IOException ioE) {
                    System.err.println("\nFailed to transform the object");
                }
                bytes = bos.toByteArray();
            } catch (FileNotFoundException fnfE) {
                System.err.println("\nFailed to open the file " + filePath);
            } finally {
                return bytes;
            }
        } else
            System.err.println(ERROR_MESSAGE);

        return null;
    }
}

Related

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