Android File to Byte Array Read readFileToByteArray(String filePath)

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

Description

read File To Byte Array

License

Apache License

Declaration

public static byte[] readFileToByteArray(String filePath) 

Method Source Code

//License from project: Apache License 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Main{
    private static final Logger logger = LoggerFactory
            .getLogger(FileUtil.class);
    public static byte[] readFileToByteArray(String filePath) {
        if (StringUtil.isEmpty(filePath)) {
            return null;
        }//from ww  w  .j  a v a2 s.  c o  m
        File file = new File(filePath);

        return readFileToByteArray(file);
    }
    public static byte[] readFileToByteArray(File file) {
        byte[] fileBytes = new byte[(int) file.length()];

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            int offset = 0;
            int count = (int) file.length();
            int temp = 0;

            while ((temp = fis.read(fileBytes, offset, count)) > 0) {
                offset += temp;
                count -= temp;
            }
        } catch (FileNotFoundException e) {
            logger.error("readFile", e);
        } catch (IOException e) {
            logger.error("readFile", e);
        } catch (Exception e) {
            logger.error("readFile", e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    logger.error("readFile", e);
                }
            }
        }

        return fileBytes;
    }
}

Related

  1. getFileAsByteArrayOutputStream( File file)
  2. readBytes(@NotNull File file)
  3. readBytes(@NotNull String filePath)
  4. readFileBytes(File fx)
  5. readFileToByteArray(File file)
  6. fileToBytes(String filePath)
  7. fileToByte(String filePath)
  8. getBytesFromFile(File file)
  9. readBytes(File file)