How do I convert a java.io.File
to a byte[]
?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
If you want to read bytes into a pre-allocated byte buffer, this answer may help.
Your first guess would probably be to use
InputStream read(byte[])
. However, this method has a flaw that makes it unreasonably hard to use: there is no guarantee that the array will actually be completely filled, even if no EOF is encountered.Instead, take a look at
DataInputStream readFully(byte[])
. This is a wrapper for input streams, and does not have the above mentioned issue. Additionally, this method throws when EOF is encountered. Much nicer.Documentation for Java 8: http://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html
Guava has Files.toByteArray() to offer you. It has several advantages:
If you don't have Java 8, and agree with me that including a massive library to avoid writing a few lines of code is a bad idea:
Caller is responsible for closing the stream.
Using the same approach as the community wiki answer, but cleaner and compiling out of the box (preferred approach if you don't want to import Apache Commons libs, e.g. on Android):
Basically you have to read it in memory. Open the file, allocate the array, and read the contents from the file into the array.
The simplest way is something similar to this:
This has some unnecessary copying of the file content (actually the data is copied three times: from file to
buffer
, frombuffer
toByteArrayOutputStream
, fromByteArrayOutputStream
to the actual resulting array).You also need to make sure you read in memory only files up to a certain size (this is usually application dependent) :-).
You also need to treat the
IOException
outside the function.Another way is this:
This has no unnecessary copying.
FileTooBigException
is a custom application exception. TheMAX_FILE_SIZE
constant is an application parameters.For big files you should probably think a stream processing algorithm or use memory mapping (see
java.nio
).