Java Read File Bute by Byte Without Using Ram
Hello guys, Java programmers oftentimes face scenarios in real-world programming, where they need to load data from a file into a byte array, it could exist text or binary file. 1 case is to convert the contents of a file into String for display. Unfortunately, Coffee'southward File class, which is used to represent both files and directories, doesn't have a method say toByteArray(). It just holds path and allows you to perform certain operations similar opening and closing file, but doesn't let you to straight catechumen File to a byte array. Anyway, no need to worry as at that place are several other means to read File into a byte array and you will acquire those in this Java file tutorial.
If you are a fan of Apache commons and Google Guava like me, so yous may already familiar with i-liner code, which can quickly read a file into a byte array; if not, then this is the right time to explore those API.
In this tutorial, we are going to see seven different examples to read File to a byte assortment, some by using third party libraries, and others past using JDK 6 and JDK 7 core Java libs.
Depending upon your choice, you can use any of the following methods to convert file information into bytes. One matter to keep in mind is what you are doing with byte assortment; if you are creating String from a byte array, then beware with grapheme encoding. You may need to find out correct character encoding by reading metadata information like Content-Type of HTML pages and of XML documents.
While reading XML documents, it's a bad idea to first read an XML file and shop it in a String. Instead, information technology'southward better to pass InputStream to XML parsers, and they will figure out the encoding themselves correctly.
1 more affair to note is that you cannot read file larger than 2GB into a single byte array, yous demand multiple byte arrays for that. This limitation comes from the fact that the array index in Java is of int type, whose maximum value is 2147483647, roughly equivalent to 2GB.
Btw, I am expecting that you lot are familiar with basic Java Programing and Java API in general.
7 means to read a file into a byte array in Java
Without wasting any more of your time, here are all the vii ways to load a file into a byte array in Java:
1) Using Apache Commons IOUtils
This is 1 of the easiest ways to read a file data into a byte array, provided you don't hate 3rd-party libraries. It'due south productive because you don't need to code it from scratch, worrying about exception handling, etc.
| 1 | |
The IOUtils.toByteArray(InputStream input) Gets the contents of an
InputStream as a byte[]. This method also buffers the input internally, and then there is no need to utilise a BufferedInputStream, but information technology'southward non naught-rubber. It throws NullPointerException if the input is zippo.
2) Using Apache Eatables FileUtils
The FileUtils grade from org.apache.eatables.io package provides a general file manipulation facility like writing to a file or reading from a file. This method is used to read the contents of a file into a byte assortment, and the good matter about this is that the file is ever closed.
| ane | |
three) Using FileInputStream and JDK
This is the archetype way of reading the file'south content into a byte assortment. Don't forget to close the stream once done. Hither is the lawmaking to read a file into a byte array using FileInputStream form in Java:
| 01 02 03 04 05 06 07 08 09 x 11 12 thirteen 14 15 sixteen 17 | |
In product, use finally cake to close streams to release file descriptors.
4) Using Google Guava Files class
Files grade of Google Guava provides utility methods for working with files, like converting files to a byte array, to string with specified charset, copy, move, etc. Files.toByteArray() method reads all bytes from a file into a byte array and throws IllegalArgumentException if the file size is bigger than the largest possible byte array (two^31 – ane).
| ane | |
This approach of reading files content into byte array has several advantages, start of all, you don't need to reinvent the wheel. 2nd, information technology uses NIO for reading a file, which will perform ameliorate than stream IO. You as well don't demand to worry about handling exceptions and closing streams, equally Guava does for y'all.
5) Using Guava'south ByteStreams utility
Guava'southward ByteStreams class provides utility methods for working with byte arrays and I/O streams. The toByteArray() takes an InputStream and reads all bytes into a byte array but it does not close the stream, so you demand to close information technology past yourself.
This is ane reason, I don't prefer this method, the Java vii example we saw in the last section takes care of closing streams.
| 1 | |
By the way, If you are using Java in-memory constraint environment like
Android, then consider using obfuscator like proguard to remove unused classes from tertiary-party libraries. For case, Guava past default adds more than than 2MB to an APK. But with Proguard it comes down to about 250KB
6) Using JDK 7 NIO Files and Path
If yous are using Java seven, then this is the best way to catechumen File into a byte array. It allows you to read all bytes from a file and capture them in a byte array. All you need to know is the path of the file.
Here is the lawmaking sample to read a file in Java 7:
| 1 two | |
The biggest advantage of this approach is that it doesn't crave any third-party libraries. It's also a static method, which makes it very convenient. It as well ensures that the file is closed when all bytes accept been read or an I/O error, or other runtime exception, is thrown. Something Java has been lacking from the showtime edition.
By the mode, this method is merely intended for elementary use where it is convenient to read all bytes into a byte array. It is not intended for reading big files and throws OutOfMemoryError, if an array of the required size cannot be allocated, for instance, the file is larger than 2GB.
Past the fashion, if you only have File object and not Path so you lot can as well use
File.toPath() to convert File to Path in JDK 1.vii.
7) Using RandomAccessFile in Java
You can as well use RandomeAccessFile to catechumen File into an array of bytes as shown below, though you tin can also use read(byte[]) method, it'due south better to utilise readFully.
| i 2 3 4 5 6 7 | |
Also, note that RandomAccessFile is not thread-safe. So, synchronization may be needed in some cases.
Last affair, some of the code here is not production quality, equally they are not handling exceptions properly. In real-world, all file handling code must close streams in finally block to release file descriptor associated with that, failure to do and so may result in you java.io.IOException: Too many open up files error.
Sometimes you can expect libraries similar Apache eatables IO for closing streams properly, as seen below from a code snippet from
FileUtils class of Apache Commons IO, the closeQuietly() methods close a stream ignoring nulls and exceptions.
| 01 02 03 04 05 06 07 08 09 10 11 12 13 xiv 15 16 | |
but information technology'due south not always true, as Google Guava's ByteStreams.toByteArray method doesn't shut the stream. It's ameliorate to bank check documentation before using a detail method in product lawmaking. In general, information technology's better to employ JDK API if bachelor and that'south why a proficient knowledge of JDK goes a long way to becoming an expert Java programmer.
Java Program to Read A file into Byte Array in Java
Here is our consummate Coffee program to read a file into a byte assortment in Java. This combines all the 6 approaches I have shown above. You tin copy-paste this example and run in your favorite IDE like Eclipse, NetBeans, or IntelliJIDEA.
| 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095 096 097 098 099 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | |
That'southward all on this tutorial of 7ways to read a file into a byte assortment in Java. Now you know that there are multiple ways to read the file in Java, some by using 3rd party libraries like Apache Commons IO, Google Guava, Apache MINA, and others by just employing standard JDK file input-output classes. Depending upon your requirement, you tin use any of these solutions to read file data into a byte in Java. Go along an center on grapheme encoding if you are converting byte array to String.
Also, remember that array in Java tin can only hold a express amount of information every bit it's length cannot exceed Integer.MAX_VALUE (2GB). Then y'all cannot convert a large file into a single-byte assortment, though y'all can read large data using input stream, you need to process them in chunks or using multiple byte arrays.
If you like this article and want to learn more virtually improved file IO in contempo Java version, delight cheque the following tutorials:
- The Complete Coffee Programmer RoadMap (guide)
- 3 ways to read a file line by line in Java 8 (examples)
- x Courses to learn Coffee in 2020 (courses)
- How to read a text file line past line using BufferedReader in Java? (reply)
- 15 things Java Programmers can acquire in 2020 (article)
- How to employ a memory-mapped file in Coffee? (reply)
- Meridian five Skills to Crevice Coding Interviews (skills)
- How to read an XML file equally String in Java? (tutorial)
- How to read/write Excel (both XLS and XLSX) files in Coffee using Apache POI? (tutorial)
- 2 ways to parse CSV file in Java? (answer)
- How to delete a directory with files in Coffee? (answer)
- How to parse XML file in Java using SAX parser? (guide)
- How to catechumen JSON to Object in Coffee? (example)
- How to read XML file in Java using JDOM parser? (tutorial)
- How to parse a big JSON file using Jackson Streaming API? (example)
- How to read a file in one line in Java viii? (example)
- How to copy File in Java? (example)
- How to generate MD5 checksum for file in Java? (solution)
- How to read/write RandomAccessFile in Java? (example)
Thanks for reading this article then far. If yous find this Java File tutorial useful then please share information technology with your friends and colleagues. If yous take whatever questions or feedback and then please drop a note.
Source: https://www.javacodegeeks.com/2020/04/7-examples-to-read-file-into-a-byte-array-in-java.html
0 Response to "Java Read File Bute by Byte Without Using Ram"
Post a Comment