Write and Read File in Java

This tutorial will explain how to write and read file in Java. The java.io package contains two classes, InputStream and OutputStream, from which most of the other classes in the package drive.

In this tutorial, We will learn about these both two classes and see the use of these class.

FileInputStream and FileOutputStream classes are used to read and write data in the file. In another word, they are used for file handling in java.

Let’s see the uses of both of the classes in details.


Write and Read file in Java with Example


Read File in Java or Java FileInputStream

The InputStream class is an abstract superclass that provides a minimal programming interface and a partial implementation of input streams. The InputStream class defines methods for reading bytes or arrays of bytes.

It obtains input bytes from a file.  It is used for reading streams of raw bytes such as image data. You typically read data from an InputStream by calling the read() method. The read() method return and containing the byte value of the byte read. If there is no more data to be read, the read() method typically returns -1.

Here is a simple example:

The above code will print all data present in the file named ‘TestFile’. You can try the above code on your local machine and see the output.

Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.


Write File in Java or Java FileOutPut Stream

Java FileOutputStream is an output stream for writing data to a file. TheOutputStream class is an abstract superclass that provides a minimal programming interface and a partial implementation of output streams. OutputStream defines methods for writing bytes or arrays of bytes to the stream. An output stream is automatically opened when you create it. You can explicitly close an output stream with the close method.

If you have to write primitive values then use FileOutputStream.Instead, for character-oriented data, prefer FileWriter.But you can write byte-oriented as well as character-oriented data. Let’s understand this with an easy example –

The above code will write the String s value in the file named TestFile. The only condition is file should be present at the given location, this code will not create and write the file.

This is the way you can Write and Read file in Java. You can try the code on your local machine.

0 Comment

Leave a Reply