Java file into byte array knowledge summary and example explanation

Java converts files into byte arrays

Keywords: file, file stream, byte stream, byte array, binary

Absrtact: the demand encountered in recent work is to use HTTP to transmit binary data to the corresponding interface of the server. A series of mixed binary data such as userid and file (encrypted) need to be transmitted. This article aims to record some knowledge understanding and summary of converting files into byte arrays using Java.

FileInputStream

Reading files using FileInputStream

FileInputStream is a subclass of InputStream, which is used to read information from a file. The constructor receives a file type or a string type representing a file path.

ByteArrayOutputStream

Use bytearrayoutputstream to read out the file data in FileInputStream

Bytearrayoutputstream is used to create a buffer in memory. All data sent to the "stream" should be placed in this buffer.

Note: the write method of bytearrayoutputstream has three overloaded forms:

Write (int b) writes the specified byte

Write (byte [] b) writes the entire byte array B

Write (byte [] B, int off, int len) writes byte array B, and writes len bytes starting from the off subscript of B.

The second method is not used here, but the third method is used. In the code, the number of bytes read into buffer B is usually 1024 (because the specified length is displayed when defining b). Only when reading to the end, it may not be enough 1024 bytes, and the actual number of bytes read will also be read. However, when writing to the buffer, if the number of bytes written is not specified, That is, if len is not specified, the whole B will be written. Even if there is only part of B, 1024 bytes will still be written. This will cause that the byte array obtained when tobytearray is used is not the actual length!

This writes the file stream from InputStream to bytearrayoutputstream.

Use the tobytearray() method of bytearrayoutputstream to get the byte array of the file.

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>