Java converts files into byte array
Keywords: file, file stream, byte stream, byte array, binary
Abstract: The recent requirement encountered in work is to use http to transmit binary data to the corresponding interface of the server, and a series of mixed binary data such as userId and file (encrypted). This article aims to record some knowledge and summary of converting files into byte arrays using Java.
FileInputStream
Read files with 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 the file path.
File file = new File("filePath");FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream
Use ByteArrayOutputStream to read out the file data in FileInputStream
ByteArrayOutputStream is used to create a buffer in memory, and all data sent to the "stream" must be placed in this buffer.
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: The write method of ByteArrayOutputStream has three overloaded forms:
write(int b)
Write specified bytes
write(byte[] b)
Write to the entire byte array b
write(byte[] b, int off, int len)
Write to the byte array b, start from the off-th subscript of b, and write len bytes.
The second one is not used here, but the third one is used. In the code, the number of reads into buffer b is generally 1024 (because the specified length is displayed when b is defined). Only when the end is read, it may not be enough 1024 bytes, and the actual number of read bytes will be read. However, when writing to the buffer, if the number of writes is not specified, that is, len is not specified, then the entire b will be written. Even if there is only a part of the content in b, 1024 bytes will still be written. This will cause the resulting byte array is not the actual length when using toByteArray!
This writes the file stream from the InputStream into the ByteArrayOutputStream.
Use the toByteArray() method of ByteArrayOutputStream to obtain the byte array of the file.
byte[] fileByte = bos.toByteArray();
Thank you for reading, I hope it can help you. Thank you for your support for this site!