How to convert a file to a byte array in Java

A method created to store PDF files and CSV files in the BLOB type of Oracle. Until now, I have rarely dealt with byte arrays, so I will write it down so that I will not forget it in the future.

Operating environment

Method made

    public byte[] convertFile(File file) {
        try (FileInputStream inputStream = new FileInputStream(file);) {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            while(true) {
                int len = inputStream.read(buffer);
                if(len < 0) {
                    break;
                }
                bout.write(buffer, 0, len);
            }
            return bout.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Modified version of the method I made

Based on what you told me in the comments, I will write some modified methods.

Method ①

A version that fixes the point that the infinite loop by while is not cool and forgetting to close ByteArrayoutputStream. The method described later is simpler, so if you have Java 7 or above, you should use method ② or later.

    public byte[] convertFile(File file) {
        File file = new File(dir + name);
        try (FileInputStream inputStream = new FileInputStream(file);
            ByteArrayOutputStream bout = new ByteArrayOutputStream();) {
           byte[] buffer = new byte[1024];
           int len = 0;
           while((len = inputStream.read(buffer)) != -1) {
               bout.write(buffer, 0, len);
           }
           return bout.toByteArray();
       } catch (Exception e) {
           e.printStackTrace();
       }
        return null;
    }

Method ②

How to use apache.commons.compress.utils.IOUtils.toByteArray. Any environment where you can add a library is OK.

    public byte[] convertFile(File file) throws IOException {
        FileInputStream inputStream = new FileInputStream(file);
        return IOUtils.toByteArray(inputStream);
    }

Method ③

How to use java.nio.file.Files.readAllBytes (). Note that it can only be used with Java 7 or above.

public byte[] convertFile(File file) throws IOException {
    return Files.readAllBytes(file.toPath());
}

Method ④

How to use java.io.InputStream.transferTo (). Note that it can only be used with Java 9 or above.

    public byte[] convertFile(File file) throws IOException {
        FileInputStream inputStream = new FileInputStream(file);
        return inputStream.transferTo(outputStream);
    }

Miscellaneous feelings

--This time it's Java 8, so using java.nio.file.Files.readAllBytes () may be the simplest with the fewest lines. --Failed to run into the method of using OutputStream and InputStream. I should have investigated more before implementing it ...

Recommended Posts

How to convert a file to a byte array in Java
Convert a Java byte array to a string in hexadecimal notation
How to convert A to a and a to A using AND and OR in Java
Gzip-compress byte array in Java and output to file
How to make a Java array
[Java] I want to convert a byte array to a hexadecimal number
[Java] How to convert a character string from String type to byte type
How to display a web page in Java
How to convert a solidity contract to a Java contract class
How to convert Java radix
[Java] Convert ArrayList to array
[Java] [For beginners] How to insert elements directly in a 2D array
How to initialize Java array
How to create a Java environment in just 3 seconds
How to jump from Eclipse Java to a SQL file
[Java] How to convert one element of a String type array to an Int type
How to make a Java container
How to learn JAVA in 7 days
How to convert erb file to haml
[Java] How to create a folder
Log output to file in Java
How to use classes in Java?
How to name variables in Java
[Java] Convert array to ArrayList * Caution
How to concatenate strings in java
How to read your own YAML file (*****. Yml) in Java
How to change a string in an array to a number in Ruby
Read WAV data as a byte array in Android Java
How to store a string from ArrayList to String in Java (Personal)
How to add the same Indexes in a nested array
How to develop and register a Sota app in Java
How to simulate uploading a post-object form to OSS in Java
For Java beginners: List, Map, Iterator / Array ... How to convert?
[Ruby] How to batch convert strings in an array to numbers
How to save a file with the specified extension under the directory specified in Java to the list
[Xcode] How to add a README.md file
How to make a Java calendar Summary
When seeking multiple in a Java array
How to implement date calculation in Java
How to implement Kalman filter in Java
Multilingual Locale in Java How to use Locale
[Java] How to use the File class
How to make a jar file with no dependencies in Maven
How to insert a video in Rails
[Ruby] I want to put an array in a variable. I want to convert to an array
How to add a new hash / array
How to implement a job that uses Java API in JobScheduler
How to add jar file in ScalaIDE
How to create a new Gradle + Java + Jar project in Intellij 2016.03
How to do base conversion in Java
[Introduction to Java] How to write a Java program
How to automatically operate a screen created in Java on Windows
How to make a Discord bot (Java)
Convert SVG files to PNG files in Java
How to implement coding conventions in Java
How to embed Janus Graph in Java
Cast an array of Strings to a List of Integers in Java
How to print a Java Word document
How to get the date in java
How to publish a library in jCenter
Sample to unzip gz file in Java