Java – Reading & Writing to Files

Reading and Writing to Files in Java

We have covered Streams(Input Stream and OuputStream) in the previous lesson. We also treated Standard Streams.  Now, you will learn about FileInputStream and FileOutputStream. You use these classes to read and write to files.

 

Content

  1. FileInputStream
  2. FileOutputStream
  3. Program to Write to a File
  4. Program to Read from a File
  5. Watch the Video

 

1. FileInputStream

You use this  stream to read data from files. But before you can read data, you need to create a new FileInputStream object. The constructor take a the filepath as parameter. This is shown below

     InputStream fs = new FileInputStream("C:/programs/test.txt");

So this code creates a new InputStream object fs. The file specified in the constructor is the file you want to read from.

 

Another Method

You can also create an InputStream object by first creating a file object . Then you pass the file object to the constructor of the FileInputStream. This is shown below:

 

    File myfile = new File("C:/programs/test.txt");
    InputStream fs = new FileInputStream(myfile);

If you have created an InputStream object, then you have a number of helper methods you can use. These methods would help you read data from the file of perform other operations

 

SN Method brief description
1 close() throws IOException{}

You use this method to close the file output stream. It also releases any system resources associated with the file. It throws an IOException if something goes wrong.

2 finalize() throws IOException {}

This method is used to clean up the connection to the file. It ensures that the close method of the stream is called when there are no more references to the stream. Also throws an IOException.

3 read(int r) throws IOException{}

You use this method to read  the specified byte of data from the InputStream. It returns an int value. Returns the next byte of data. But  -1 is returned if it’s the end of the file.

4 read(byte[] r) throws IOException{}

You use this method to read r.length bytes from the input stream into a byte array. It returns the total number of bytes read. It returns -1 if it is end of file.

5 available() throws IOException{}

It it used to get the number of byte that can be read from this file input stream. Returns an int value

Table 1.0: Method Available for FileInputStream

 

2. FileOutputStream

Unlike the FileInputStream, you use this stream  to create a write to a file. You can also use it to create a file. So if a specified file does not exist, it can create it before writing to it.

But before writing, the file has to be opened.

To write to a file, you can use one of two methods:

 

Method 1: Create a FileOutputStream object and give it the filepath. This is shown below:

   OutputStream fos = new FileOutputStream("C:/data/out.txt");

 

Method 2: Create a file object. Then pass the file object as parameter to the FileOutpuStream constructor. For example, see below:

   File outfile = new File("C:/data/out.txt");
   OutputStream fos = new FileOutputStream(outfile);

 

Just like FileInputStream, there are also methods available for FileOutputStream. Therefore, you use these methods to write data to file and perform other file operations. The list of method is provided below in Table 1.1. You probably should attempt to used them. The video lesson can help you.

 

SN Method and brief description
1 close() throws IOException{}

You use this method to close  the stream. It also releases any system resources associated with the file. It throws an IOException.

2  finalize() throws IOException {}

You use this method to up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.

3 write(int w) throws IOException{}

You use this method to write the given byte to the output stream.

4 write(byte[] w)

This method also writes w.length bytes from the specified byte array to the OutputStream.

Table 1.1: Methods for OutputStream

 

 

3. Program to Write to File

We would write a program to create a file and write a list of items to the file. So we would use three classes:

  • File: Creates a file  object taking the filepath as parameter
  • OutputStream: Creates a FileOutputStream object taking a File object as parameter
  • PrintWirter: This is use to write data so that i could be readable. It takes the FileOutputStream object as parameter

Find the code below. Also try to run it yourself and get used to it.

 

import java.io.*;
public class FileStreamDemo {
	public static void main(String[] args) {
		
		try {
			byte[] byteToWrite = {2,5,77,43,78,23,4,6};
			
			File ofile = new File("D:/data/javadata.txt");
			
			OutputStream ofs = new FileOutputStream(ofile);
			
			PrintWriter ps = new PrintWriter(ofs);
						
			for(byte item : byteToWrite) {
				ps.println(item);
			}
			
			ps.close();
			ofs.close();			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Listing 1.0: Program to write to a file

 

 

4. Program to Read from a File

Similar to writing to a file, we are going to read from a file. So we would read the content of the file and display it to the console.

 

import java.io.*;
public class FileStreamDemo {
	
	public static void main(String[] args) {
		
		try {
			File infile = new File("D:/data/javadata.txt");
			InputStream ifs = new FileInputStream(infile);
			
			int size = ifs.available();
			
			for(int i =1; i<size; i++) {
				System.out.println(ifs.read());
			}
			
			ifs.close();
		}
		catch(IOException e) {
			e.printStackTrace();
		}	}
}

Listing 1.1: Program to Read the content of a file

 

I recommend you also watch the video to get understand it better.

5. Watch the Video