Java converts files into byte array knowledge summaries and case studies
- 2020-05-26 08:27:21
- OfStack
Java converts files into byte arrays
Keywords: file, file stream, byte stream, byte array, base 2
Abstract: recently, I met with the requirement of using http to transmit binary data to the corresponding interface of the server, so I need to transmit the mixed binary data of series 1, such as userId and file(after encryption). The purpose of this article is to document some of my understanding and summarization of converting files into byte arrays using Java.
FileInputStream
Read the file using FileInputStream
FileInputStream is a subclass of InputStream used to read information from a file, and the constructor receives an File type or an String type representing a file path.
File file = new File("filePath");
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream
Read the file data in FileInputStream using ByteArrayOutputStream
ByteArrayOutputStream is used to create a buffer in memory where all data sent to the "stream" is placed.
ByteArrayOutputStream bos = new ByteArrayOutputStream(fis);
byte[] b = new byte[1024];
int len = -1;
while((len = fis.read(b)) != -1) {
bos.write(b, 0, len);
}
Note: ByteArrayOutputStream's write method has three overloaded forms:
write(int b)
Write to specified byte
write(byte[] b)
Write the entire byte array b
write(byte[] b, int off, int len)
Write the byte array b, starting with the off subscript of b, and write len bytes.
In 2 there is no use, but use, is the third, in the code every time for quantity of the read buffer b, 1 kind is 1024 (because when defining b) show that specifies the length, only when the read to the end, may be not enough 1024 bytes, also can read the actual bytes read, but at the time of the buffer, if you do not specify write number, namely do not specify a len, then the whole b write, even if only 1 part of b, but will still write to 1024 bytes. This results in the fact that when toByteArray is used, the resulting byte array is not the actual length!
This writes the file stream from InputStream to ByteArrayOutputStream.
Get the byte array of the file using ByteArrayOutputStream's toByteArray() method.
byte[] fileByte = bos.toByteArray();
Thank you for reading, I hope to help you, thank you for your support of this site!