Home Java How to Read a File in Java

How to Read a File in Java

Taking input from the user is an important part of creating a program, and there can be many ways to take input to use it in our program. One such way is reading data from a file. Taking input from the file may be a bit tricky and difficult to grasp, but it is beneficial for storing a large amount of data.

Read Data From a File

Scanner class is used to take input in a java program. Thus, we can use the scanner class to read data from a file. System.in is passed as an argument in the scanner object, which specifies taking input from the keyboard so in place of System.in. We can pass a file object as shown.

File myFile = new File("Customers.txt");
Scanner inputFile = new Scanner(myFile);

So the first statement creates an object of the file, the File keyword is used to define a file, representing the customers.txt file. The second line takes input and passes a reference to the file object as its input. For this, we need to import two libraries.

import java.util.Scanner; // Needed for Scanner class
import java.io.*; //needed for file and IO Exception

After we have finished reading from the file, the following statement closes the file that is the object’s source of output:

inputFile.close();

Reading Lines From a File

The nextline() method in java is used to read a line of input and returns a string as output. The nextline() method can also be used to read input from files. Now, to see how this works, we first need to create a file in the same directory as the code. Create a file named hello.txt and follow the example illustrated below:

 import java.util.Scanner; // Needed for Scanner class
 import java.io.*; // Needed for File and IOException

 /**
 This program reads the first line from a file.
 */
 public class ReadFirstLine
 {
   public static void main(String[] args) throws IOException
   {

   // Open the file.
   File file = new File("Hello.txt");
   Scanner inputFile = new Scanner(file);

   // Read the first line from the file.
   String line = inputFile.nextLine();

   // Display the line.
   System.out.println("The first line in the file is:");
   System.out.println(line);

   // Close the file.
   inputFile.close();
   }
 }

Now, since java is an object-oriented language, all the written code should be inside a class. The above program opens a file named Hello.txt, reads the first line, and displays the output.

When a file is opened for reading, a special value known as reading position is maintained for a file even though we cannot see it, but it is there internally. A file’s read position marks the location of the next item it will read. When a file is opened, the read position points to the first item, and after reading that item and then the read position moves on to the next item.

What do we do if want to read several lines until the end of file ? We will simply loop through the whole file reading process.

Detecting the End of File

Sometimes, we need to read the content of the whole file and are unaware of the number of lines we should loop through. In this situation, we use the while loop and the hasNext() method. The hasNext() method is a function of the scanner class that determines whether the file has more data to read or not. If there is more data to read, the hasNext() method returns true, and when we reach the end of the file, it returns false.

 import java.util.Scanner; // Needed for the Scanner class
 import java.io.*; // Needed for the File and IOException

 /**
 This program reads data from a file.
 */

 public class FileRead
 {
   public static void main(String[] args) throws IOException
   {
     // Open the file.
     File file = new File("days.txt");
     Scanner inFile = new Scanner(file);

     // Read lines from the file until no more are left.
     while (inFile.hasNext())
     {
     // Read the next day.
     String days = inFile.nextLine();

     // Display the last day read.
     System.out.println(days);
     }

     // Close the file.
     inFile.close();
     }
   }

Reading a Binary File

A binary file is not like a text file because it does not have data in text form. Therefore, we cannot view the contents of a binary file. A binary file is much more efficient than a text file because there is minimal conversion when reading it.

To deal with binary files we have the following class:

  • FileInputStream: This class allows you to open a binary file and establish a connection with it. But, it provides only basic functionality like reading bytes.
  • DataInputStream: This class is used along with FileInputStream and allows you to read data of the primitive type and string objects from the binary file.

Now we open a binary file for reading input. We take input from a .dat file as shown below in the code snippet.

FileInputStream fstream = new FileInputStream("Info.dat");
DataInputStream inputFile = new DataInputStream(fstream);

Here we have opened an info.dat file. When the DataInputStream object has been created, we can use it to read the data from the binary file. The code below shows how we can read a binary file and then display numbers from it.

import java.io.*;

 /**
 This program opens a binary file, reads
 and displays the contents.
 */

 public class ReadBinaryFile
 {
 public static void main(String[] args) throws IOException
 {
 int number; // A number read from the file
 boolean endOfFile = false; // EOF flag

 // Create the binary file input objects.
 FileInputStream fstream =
 new FileInputStream("Integers.dat");
 DataInputStream inFile =
 new DataInputStream(fstream);

 System.out.println("Reading numbers from the file:");

   // Read the contents of the file.
   // read until End of File is reached
   while (!endOfFile)
   {
   try
   {
   number = inFile.readInt();
   System.out.print(number + " ");
   }
   catch (EOFException e)
   {
   endOfFile = true;
   }
   }

   System.out.println("\nDone.");

   // Close the file.

     inFile.close();
 }
 }

The above code is linked to the code below. The file is first opened for writing in the code below, and an array of numbers is written into the file, as shown below. This .dat file is used in the above code for reading data from a binary file. The output of the above code will be the number array shown in the code below.

import java.io.*;

 /**
 This program opens a binary file and writes the contents
 of an int array to the file.
 */

 public class WriteBinaryFile
 {
   public static void main(String[] args)
   throws IOException
   {
   // An array to write to the file
   int[] numbers = { 1, 3, 5, 7, 9, 11, 13 };

   // Create the binary output objects.
   FileOutputStream fstream =
   new FileOutputStream("Integers.dat");
   DataOutputStream outFile =
   new DataOutputStream(fstream);

   System.out.println("Writing the numbers to the file...");

   // Write the array elements to the file.
   for (int i = 0; i < numbers.length; i++)
   outFile.writeInt(numbers[i]);

   System.out.println("Done.");

   // Close the file.
   outFile.close();
   }
 }

Conclusion

So the question that arises is that “Why to read input from a file when we can simply read it from the keyboard?”. The answer to this question is that file processing is efficient and flexible. Furthermore, filing is used to store and display a large amount of data, which would not be possible on a console.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More