936

InputStream全体をバイト配列に読み込むにはどうすればよいですか?

4

33 に答える 33

1239

Apache Commons IOを使用して、このタスクおよび同様のタスクを処理できます。

この型には、を読み取って返すIOUtils静的メソッドがあります。InputStreambyte[]

InputStream is;
byte[] bytes = IOUtils.toByteArray(is);

内部的には、これによりaが作成ByteArrayOutputStreamされ、バイトが出力にコピーされてから、が呼び出されますtoByteArray()。4KiBのブロックでバイトをコピーすることにより、大きなファイルを処理します。

于 2009-08-12T07:35:54.517 に答える
480

から各バイトを読み取り、InputStreamに書き込む必要がありますByteArrayOutputStream

次に、以下を呼び出して、基になるバイト配列を取得できますtoByteArray()

InputStream is = ...
ByteArrayOutputStream buffer = new ByteArrayOutputStream();

int nRead;
byte[] data = new byte[16384];

while ((nRead = is.read(data, 0, data.length)) != -1) {
  buffer.write(data, 0, nRead);
}

return buffer.toByteArray();
于 2009-08-12T07:30:30.427 に答える
401

最後に、20 年後、Java 9のおかげで、サードパーティのライブラリを必要としないシンプルなソリューションがあります。

InputStream is;
…
byte[] array = is.readAllBytes();

便利なメソッドreadNBytes(byte[] b, int off, int len)transferTo(OutputStream)、繰り返し発生するニーズへの対応にも注意してください。

于 2016-06-07T13:50:17.000 に答える
140

バニラ JavaDataInputStreamとそのreadFullyメソッドを使用します (少なくとも Java 1.4 以降で存在します):

...
byte[] bytes = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(bytes);
...

この方法には他にもいくつかのフレーバーがありますが、私はこのユース ケースでは常にこれを使用しています。

于 2012-01-25T14:31:13.903 に答える
127

Google Guavaを使用する場合は、次を使用するのと同じくらい簡単ByteStreamsです。

byte[] bytes = ByteStreams.toByteArray(inputStream);
于 2014-05-04T10:37:42.000 に答える
19

画像として本当に必要byte[]ですか?byte[]画像ファイルの完全なコンテンツ、画像ファイルの形式、または RGB ピクセル値でエンコードされたものに正確に何を期待しますか?

ここでの他の回答は、ファイルを .csv ファイルに読み込む方法を示していますbyte[]。あなたbyte[]にはファイルの正確な内容が含まれており、画像データを操作するにはそれをデコードする必要があります。

画像を読み取る (および書き込む) ための Java の標準 API は ImageIO API で、パッケージに含まれていますjavax.imageio。たった 1 行のコードで、ファイルから画像を読み込むことができます。

BufferedImage image = ImageIO.read(new File("image.jpg"));

これにより、BufferedImageではなくが得られますbyte[]。画像データを取得するには、 を呼び出しgetRaster()ますBufferedImage。これによりRaster、ピクセル データにアクセスするためのメソッドを持つオブジェクトが得られます (複数のgetPixel()/getPixels()メソッドがあります)。

javax.imageio.ImageIOjava.awt.image.BufferedImageなどの API ドキュメントを検索しますjava.awt.image.Raster

ImageIO はデフォルトで多くの画像形式をサポートしています: JPEG、PNG、BMP、WBMP、GIF。より多くのフォーマットのサポートを追加することができます (ImageIO サービス プロバイダー インターフェイスを実装するプラグインが必要です)。

次のチュートリアルも参照してください:イメージの操作

于 2009-08-12T08:14:19.933 に答える
15

Apache commons-io ライブラリを使用したくない場合、このスニペットは sun.misc.IOUtils クラスから取得されます。これは、ByteBuffers を使用した一般的な実装よりもほぼ 2 倍高速です。

public static byte[] readFully(InputStream is, int length, boolean readAll)
        throws IOException {
    byte[] output = {};
    if (length == -1) length = Integer.MAX_VALUE;
    int pos = 0;
    while (pos < length) {
        int bytesToRead;
        if (pos >= output.length) { // Only expand when there's no room
            bytesToRead = Math.min(length - pos, output.length + 1024);
            if (output.length < pos + bytesToRead) {
                output = Arrays.copyOf(output, pos + bytesToRead);
            }
        } else {
            bytesToRead = output.length - pos;
        }
        int cc = is.read(output, pos, bytesToRead);
        if (cc < 0) {
            if (readAll && length != Integer.MAX_VALUE) {
                throw new EOFException("Detect premature EOF");
            } else {
                if (output.length != pos) {
                    output = Arrays.copyOf(output, pos);
                }
                break;
            }
        }
        pos += cc;
    }
    return output;
}
于 2014-09-17T14:04:14.287 に答える
9
Input Stream is ...
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int next = in.read();
while (next > -1) {
    bos.write(next);
    next = in.read();
}
bos.flush();
byte[] result = bos.toByteArray();
bos.close();
于 2010-06-07T08:59:52.987 に答える
8

@Adamski:バッファを完全に回避できます。

http://www.exampledepot.com/egs/java.io/File2ByteArray.htmlからコピーされたコード(はい、非常に冗長ですが、他のソリューションの半分のサイズのメモリが必要です。)

// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);

    // Get the size of the file
    long length = file.length();

    // You cannot create an array using a long type.
    // It needs to be an int type.
    // Before converting to an int type, check
    // to ensure that file is not larger than Integer.MAX_VALUE.
    if (length > Integer.MAX_VALUE) {
        // File is too large
    }

    // Create the byte array to hold the data
    byte[] bytes = new byte[(int)length];

    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
           && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
        offset += numRead;
    }

    // Ensure all the bytes have been read in
    if (offset < bytes.length) {
        throw new IOException("Could not completely read file "+file.getName());
    }

    // Close the input stream and return bytes
    is.close();
    return bytes;
}
于 2011-06-08T08:30:49.843 に答える
4

Java 9 では、最終的に優れたメソッドが提供されます。

InputStream in = ...;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
in.transferTo( bos );
byte[] bytes = bos.toByteArray();
于 2017-02-28T20:55:23.490 に答える
2

手遅れであることはわかっていますが、ここでは、より読みやすい、よりクリーンなソリューションだと思います...

/**
 * method converts {@link InputStream} Object into byte[] array.
 * 
 * @param stream the {@link InputStream} Object.
 * @return the byte[] array representation of received {@link InputStream} Object.
 * @throws IOException if an error occurs.
 */
public static byte[] streamToByteArray(InputStream stream) throws IOException {

    byte[] buffer = new byte[1024];
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    int line = 0;
    // read bytes from stream, and store them in buffer
    while ((line = stream.read(buffer)) != -1) {
        // Writes bytes from byte array (buffer) into output stream.
        os.write(buffer, 0, line);
    }
    stream.close();
    os.flush();
    os.close();
    return os.toByteArray();
}
于 2015-06-03T11:27:16.743 に答える
1

ガベージデータを書き込むための修正で@numanの回答を編集しようとしましたが、編集は拒否されました。この短いコードは素晴らしいものではありませんが、他にこれ以上の答えはありません。これが私にとって最も理にかなっているものです:

ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; // you can configure the buffer size
int length;

while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); //copy streams
in.close(); // call this in a finally block

byte[] result = out.toByteArray();

ところで、ByteArrayOutputStream を閉じる必要はありません。読みやすくするために省略された try/finally 構造

于 2013-03-20T07:22:25.907 に答える
1

Java 8 方式 ( BufferedReaderAdam Bienに感謝)

private static byte[] readFully(InputStream input) throws IOException {
    try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
        return buffer.lines().collect(Collectors.joining("\n")).getBytes(<charset_can_be_specified>);
    }
}

このソリューションはキャリッジ リターン('\r') を消去するため、不適切な場合があることに注意してください。

于 2017-05-03T19:56:35.947 に答える
1

それが何らかの理由でテーブルから外れている場合は、それを DataInputStream にラップします。-1 または要求したブロック全体が得られるまで、 read を使用してそれを叩いてください。

public int readFully(InputStream in, byte[] data) throws IOException {
    int offset = 0;
    int bytesRead;
    boolean read = false;
    while ((bytesRead = in.read(data, offset, data.length - offset)) != -1) {
        read = true;
        offset += bytesRead;
        if (offset >= data.length) {
            break;
        }
    }
    return (read) ? offset : -1;
}
于 2016-12-03T08:22:24.640 に答える
0

Java 7 以降:

import sun.misc.IOUtils;
...
InputStream in = ...;
byte[] buf = IOUtils.readFully(in, -1, false);
于 2016-03-20T07:56:04.700 に答える
0

これは私のコピー&ペーストバージョンです:

@SuppressWarnings("empty-statement")
public static byte[] inputStreamToByte(InputStream is) throws IOException {
    if (is == null) {
        return null;
    }
    // Define a size if you have an idea of it.
    ByteArrayOutputStream r = new ByteArrayOutputStream(2048);
    byte[] read = new byte[512]; // Your buffer size.
    for (int i; -1 != (i = is.read(read)); r.write(read, 0, i));
    is.close();
    return r.toByteArray();
}
于 2016-03-11T04:10:14.913 に答える
0

私はこれを使います。

public static byte[] toByteArray(InputStream is) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            byte[] b = new byte[4096];
            int n = 0;
            while ((n = is.read(b)) != -1) {
                output.write(b, 0, n);
            }
            return output.toByteArray();
        } finally {
            output.close();
        }
    }
于 2016-01-13T05:05:40.263 に答える
-1
/*InputStream class_InputStream = null;
I am reading class from DB 
class_InputStream = rs.getBinaryStream(1);
Your Input stream could be from any source
*/
int thisLine;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((thisLine = class_InputStream.read()) != -1) {
    bos.write(thisLine);
}
bos.flush();
byte [] yourBytes = bos.toByteArray();

/*Don't forget in the finally block to close ByteArrayOutputStream & InputStream
 In my case the IS is from resultset so just closing the rs will do it*/

if (bos != null){
    bos.close();
}
于 2011-06-01T15:22:01.893 に答える
-1

これは私にとってはうまくいきます、

if(inputStream != null){
                ByteArrayOutputStream contentStream = readSourceContent(inputStream);
                String stringContent = contentStream.toString();
                byte[] byteArr = encodeString(stringContent);
            }

readSourceContent()

public static ByteArrayOutputStream readSourceContent(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int nextChar;
        try {
            while ((nextChar = inputStream.read()) != -1) {
                outputStream.write(nextChar);
            }
            outputStream.flush();
        } catch (IOException e) {
            throw new IOException("Exception occurred while reading content", e);
        }

        return outputStream;
    }

エンコード文字列()

public static byte[] encodeString(String content) throws UnsupportedEncodingException {
        byte[] bytes;
        try {
            bytes = content.getBytes();

        } catch (UnsupportedEncodingException e) {
            String msg = ENCODING + " is unsupported encoding type";
            log.error(msg,e);
            throw new UnsupportedEncodingException(msg, e);
        }
        return bytes;
    }
于 2015-08-26T09:56:54.383 に答える
-3

以下のコード

public static byte[] serializeObj(Object obj) throws IOException {
  ByteArrayOutputStream baOStream = new ByteArrayOutputStream();
  ObjectOutputStream objOStream = new ObjectOutputStream(baOStream);

  objOStream.writeObject(obj); 
  objOStream.flush();
  objOStream.close();
  return baOStream.toByteArray(); 
} 

また

BufferedImage img = ...
ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
ImageIO.write(img, "jpeg", baos);
baos.flush();
byte[] result = baos.toByteArray();
baos.close();
于 2009-08-12T07:38:28.040 に答える