How to Read a File and Create Binary Java

In this Java File IO tutorial, we show y'all how to read and write binary files using both legacy File I/O API and new File I/O API (NIO). The legacy API (classes in the java.io.* package) is perfect for manipulating low-level binary I/O operations such as reading and writing exactly i byte at a fourth dimension, whereas the NIO API (classes in the java.nio.* parcel) is more than convenient for reading and writing the whole file at one time, and of grade, faster than the old File I/O API.

1. Agreement Byte Streams

Nosotros use byte streams to read and write data in binary format, exactly 8-bit bytes. All byte stream classes are descended from the abstract classes InputStream and OutputStream. The following class diagram depicts the main classes in the legacy File I/O API that are designed for working with binary files:

Byte Streams API

Y'all tin notice that these classes implement the AutoCloseable interface, which means that we tin use the endeavor-with-resources structure to close these streams automatically.

At the top of the bureaucracy, the abstract class InputStream defines 2 primary methods for reading bytes from an input stream:

  • read() : reads ane byte of data, returns the byte as an integer value. Return -1 if the finish of the file is reached.
  • read(byte[]) : reads a chunk of bytes to the specified byte array, up to the size of the assortment. This method returns -ane if at that place's no more data or the end of the file is reached.

Similarly, the abstract class OutputStream defines 2 primary methods for writing bytes to an output stream:

  • write(int) : writes the specified byte to the output stream.
  • write(byte[]) : writes the specified array of bytes to the output stream.

Moving down, the implementation classes FileInputStream and FileOutputStream are for reading and writing streams of raw bytes, one or multiple bytes at a time. Whereas the BufferedInputStream and BufferedOutputStream are more efficient by buffering the input stream and output stream to reduce the number of calls to the native API.

Now, let's meet some lawmaking examples.

2. Reading and Writing Binary Files Using FileInputStream and FileOutputStream

The following examples apply the FileInputStream and FileOutputStream classes to perform depression level binary I/O.

This plan copies ane file to another, one byte at a time. The source file and destination file are provided from command line'south arguments:

import java.io.*; /**  * Copy one file to another using low level byte streams, ane byte at a time.  * @author www.codejava.net  */ public class CopyFiles {     public static void main(String[] args) {  		if (args.length < 2) { 			System.out.println("Please provide input and output files"); 			Arrangement.exit(0); 		}  		Cord inputFile = args[0]; 		String outputFile = args[i];          endeavour ( 			InputStream inputStream = new FileInputStream(inputFile); 			OutputStream outputStream = new FileOutputStream(outputFile);         ) {             int byteRead = -1;              while ((byteRead = inputStream.read()) != -1) {                 outputStream.write(byteRead);             }          } catch (IOException ex) { 			ex.printStackTrace(); 		}     } }

Run this program like this:

java CopyFiles Project.nil Project1(1).zilch

This program runs very slow considering information technology copies exactly one byte at a time.

And the post-obit plan runs faster because information technology reads the whole input file into an array of bytes so write the whole array of bytes to the output file:

import java.io.*; /**  * Re-create one file to another using depression level byte streams,  * read and write a whole.at once.  * @author world wide web.codejava.net  */ public form CopyFilesOne {     public static void primary(String[] args) {  		if (args.length < 2) { 			System.out.println("Please provide input and output files"); 			System.exit(0); 		}  		String inputFile = args[0]; 		String outputFile = args[ane];          try ( 			InputStream inputStream = new FileInputStream(inputFile); 			OutputStream outputStream = new FileOutputStream(outputFile);         ) { 			long fileSize = new File(inputFile).length();             byte[] allBytes = new byte[(int) fileSize];              int bytesRead = inputStream.read(allBytes);              outputStream.write(allBytes, 0, bytesRead);          } grab (IOException ex) { 			ex.printStackTrace(); 		}     } }

And the following program runs much faster past copying a chunk of bytes at a fourth dimension (exactly 4096 bytes at a time):

import java.io.*; /**  * Copy ane file to some other using low level byte streams, 4KB at a fourth dimension.  * @author www.codejava.net  */ public class CopyFilesChunk { 	private static final int BUFFER_SIZE = 4096; // 4KB      public static void principal(Cord[] args) { 		if (args.length < 2) { 			System.out.println("Delight provide input and output files"); 			System.exit(0); 		}  		String inputFile = args[0]; 		String outputFile = args[1];          try ( 			InputStream inputStream = new FileInputStream(inputFile); 			OutputStream outputStream = new FileOutputStream(outputFile);         ) {             byte[] buffer = new byte[BUFFER_SIZE];             int bytesRead = -i;              while ((bytesRead = inputStream.read(buffer)) != -1) {                 outputStream.write(buffer, 0, bytesRead);             }          } catch (IOException ex) { 			ex.printStackTrace(); 		}     } }

The post-obit programme reads the starting time eight bytes of a file to identify if it is a PNG image format or not:

import java.io.*; /**  * This programme checks whether a file is of PNG image format or not,  * by analysing its first 8 bytes.  * @author www.codejava.internet  */ public class CheckPNG { 	private static int[] pngSignature = {137, lxxx, 78, 71, xiii, 10, 26, 10};      public static void main(String[] args) {  		if (args.length < ane) { 			System.out.println("Please provide the input file"); 			System.go out(0); 		}  		String inputFile = args[0];          try ( 			InputStream inputStream = new FileInputStream(inputFile);         ) { 			int[] headerBytes = new int[8]; 			boolean isPNG = true;  			for (int i = 0; i < 8; i++) {  				headerBytes[i] = inputStream.read();  				if (headerBytes[i] != pngSignature[i]) { 					isPNG = faux; 					break; 				} 			}  			Organization.out.println("Is PNG file? " + isPNG);          } catch (IOException ex) { 			ex.printStackTrace(); 		} 	} }

Run this program like this:

coffee CheckPNG Diagram.png

If the file is actually a PNG epitome, it prints the output: Is PNG file? true

Every bit yous tin can come across, using FileInputStream and FileOutputStream is really good for low level binary I/O such equally analyzing a file or even create your own file format.

iii. Reading and Writing Binary Files Using BufferedInputStream and BufferedOutputStream

Using BufferedInputStream and BufferedOutputStream is as same as FileInputStream and FileOutputStream . The simply difference is that a buffered stream uses an array of byte internally to buffer the input and output to reduce the number of calls to the native API, hence increasing IO functioning.

By default, both BufferedInputStream and BufferedOutputStream has an internal buffer of 8192 bytes (8KB), merely nosotros can specify a custom buffer size at initialization.

All the above examples can be re-written using buffered streams just by changing the instantiation of the streams. Here's an example:

attempt ( 		InputStream inputStream = new BufferedInputStream(new FileInputStream(inputFile)); 		OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); ) {     byte[] buffer = new byte[BUFFER_SIZE];     int bytesRead = -1;      while ((bytesRead = inputStream.read(buffer)) != -1) { 	    outputStream.write(buffer, 0, bytesRead);     } } take hold of (IOException ex) { 		ex.printStackTrace(); }

And we tin specify a custom size for the buffer like this:

int bufferSize = 16384;	// 16KB buffer size InputStream inputStream 	= new BufferedInputStream(new FileInputStream(inputFile), bufferSize); OutputStream outputStream 	= new BufferedOutputStream(new FileOutputStream(outputFile), bufferSize);

4. Reading and Writing Binary Files Using New File I/O API (NIO)

The utility class Files in the java.nio.file package provides the following methods for reading and writing binary data:

  • readAllBytes(Path path) : reads all bytes from a file and returns an array of bytes. This method is intended for reading small files, non large ones.
  • write(Path path, byte[] bytes, OpenOption... options) : writes an assortment of bytes to a file with some useful options like CREATE, TRUNCATE_EXISTING, WRITE and APPEND.

Annotation that both methods close the input and output file after done and throw IOException in case of fault.

Let's encounter an instance. The files copy program higher up can exist re-written using NIO API like this:

import java.io.*; import java.nio.file.*; /**  * Copy one file to another using low level byte streams, ane byte at a fourth dimension.  * @author www.codejava.net  */ public class CopyFilesNIO {     public static void main(String[] args) {  		if (args.length < 2) { 			Organisation.out.println("Please provide input and output files"); 			System.leave(0); 		}  		String inputFile = args[0]; 		String outputFile = args[i];          try { 			long start = System.currentTimeMillis(); 			byte[] allBytes = Files.readAllBytes(Paths.become(inputFile));  			Files.write(Paths.become(outputFile), allBytes);  			long stop = Organisation.currentTimeMillis();  			Organization.out.println("Copied in " + (finish - start) + " ms");         } take hold of (IOException ex) { 			ex.printStackTrace(); 		}     } }

Effort to run this programme and compare the time with the ones using legacy File I/O (on big files) you will run into NIO performs much faster.

API References:

  • InputStream Javadoc
  • OutputStream Javadoc
  • FileInputStream Javadoc
  • FileOutputStream Javadoc
  • Files Javadoc
  • Paths Javadoc

Related File IO Tutorials:

  • How to Read and Write Text File in Java
  • How to read text file line by line in Coffee
  • Java IO FileInputStream and FileOutputStream Examples

Other Java File IO Tutorials:

  • How to list files and directories in a directory in Java
  • Java IO - Common File and Directory Operations Examples
  • Java Serialization Basic Example
  • Understanding Java Externalization with Examples
  • How to execute Operating Arrangement Commands in Coffee
  • 3 ways for reading user'southward input from panel in Java
  • File alter notification case with Picket Service API
  • Coffee Scanner Tutorial and Lawmaking Examples

About the Writer:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Coffee in the fourth dimension of Java 1.iv and has been falling in love with Java since and so. Make friend with him on Facebook and sentry his Coffee videos you lot YouTube.

Add together comment

mileshathouty.blogspot.com

Source: https://www.codejava.net/java-se/file-io/how-to-read-and-write-binary-files-in-java

0 Response to "How to Read a File and Create Binary Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel