LoginSignup
38
41

More than 3 years have passed since last update.

Javaでファイルをバイト配列に変換する方法

Last updated at Posted at 2018-07-02

OracleのBLOB型に、PDFファイルやらCSVファイルを格納するために作ったメソッド。
今まで、バイト配列を扱うことがほぼなかったので今後も忘れないように、書き残しておこうと思います。

動作環境

  • java Java SE 8u152

作ったメソッド

    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();
        }
    }

作ったメソッド修正版

コメントにて教えていただいた点に基づいて、修正したメソッドをいくつか書きます。

メソッド①

whileによる無限ループがイケてない点と、ByteArrayoutputStreamのcloseし忘れを修正したバージョン。
後述するメソッドのほうがシンプルなので、Java 7以上ならばメソッド②以降を採用すべし。

    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;
    }

メソッド②

apache.commons.compress.utils.IOUtils.toByteArrayを使用する方法。
ライブラリを追加できる環境ならOK。

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

メソッド③

java.nio.file.Files.readAllBytes()を使用する方法。
Java 7以上じゃないと使用できないの注意。

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

メソッド④

java.io.InputStream.transferTo()を使用する方法。
Java 9以上じゃないと使用できないので注意。

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

雑感

  • 今回はJava 8なので、java.nio.file.Files.readAllBytes()を使用するのが一番行数が少なくてシンプルかも。
  • OutputStream, InputStreamを使用する方法に突っ走ってしまったのが失敗。もっと調査してから実装すれば良かった…
38
41
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
41