InputStream
全体をバイト配列に読み込むにはどうすればよいですか?
33 に答える
Apache Commons IOを使用して、このタスクおよび同様のタスクを処理できます。
この型には、を読み取って返すIOUtils
静的メソッドがあります。InputStream
byte[]
InputStream is;
byte[] bytes = IOUtils.toByteArray(is);
内部的には、これによりaが作成ByteArrayOutputStream
され、バイトが出力にコピーされてから、が呼び出されますtoByteArray()
。4KiBのブロックでバイトをコピーすることにより、大きなファイルを処理します。
から各バイトを読み取り、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();
最後に、20 年後、Java 9のおかげで、サードパーティのライブラリを必要としないシンプルなソリューションがあります。
InputStream is;
…
byte[] array = is.readAllBytes();
便利なメソッドreadNBytes(byte[] b, int off, int len)
とtransferTo(OutputStream)
、繰り返し発生するニーズへの対応にも注意してください。
バニラ JavaDataInputStream
とそのreadFully
メソッドを使用します (少なくとも Java 1.4 以降で存在します):
...
byte[] bytes = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(bytes);
...
この方法には他にもいくつかのフレーバーがありますが、私はこのユース ケースでは常にこれを使用しています。
Google Guavaを使用する場合は、次を使用するのと同じくらい簡単ByteStreams
です。
byte[] bytes = ByteStreams.toByteArray(inputStream);
画像として本当に必要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.ImageIO
、java.awt.image.BufferedImage
などの API ドキュメントを検索しますjava.awt.image.Raster
。
ImageIO はデフォルトで多くの画像形式をサポートしています: JPEG、PNG、BMP、WBMP、GIF。より多くのフォーマットのサポートを追加することができます (ImageIO サービス プロバイダー インターフェイスを実装するプラグインが必要です)。
次のチュートリアルも参照してください:イメージの操作
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;
}
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();
@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;
}
Java 9 では、最終的に優れたメソッドが提供されます。
InputStream in = ...;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
in.transferTo( bos );
byte[] bytes = bos.toByteArray();
手遅れであることはわかっていますが、ここでは、より読みやすい、よりクリーンなソリューションだと思います...
/**
* 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();
}
ガベージデータを書き込むための修正で@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 構造
Java 8 方式 ( BufferedReaderとAdam 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') を消去するため、不適切な場合があることに注意してください。
それが何らかの理由でテーブルから外れている場合は、それを 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;
}
Java 7 以降:
import sun.misc.IOUtils;
...
InputStream in = ...;
byte[] buf = IOUtils.readFully(in, -1, false);
これは私のコピー&ペーストバージョンです:
@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();
}
私はこれを使います。
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();
}
}
/*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();
}
これは私にとってはうまくいきます、
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;
}
以下のコード
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();