Java read file using 5+ methods [Easy Examples]

 

Introduction to Java read file using various methods

A file is a container in a computer system for storing information. Files used in computers are similar in features to that of paper documents used in library and office files. There are different types of files such as text files, data files, directory files, binary and graphic files, and these different types of files store different types of information. Different programming languages provide us different operations to be performed on these files.

In java, we can create, read and write on files using various. If you want to learn how to create and write on file in java then you can follow Java create & write to file Examples [Multiple Methods]

Advertisement

In this article, we will learn how we can read a file in java using various methods including Java desktop, FileInputStream,BufferedReader, FileReader, and Scanner class. All in all, this tutorial will contain all the necessary information and examples that you need to learn in order to start working with files in java.

 

Different methods to read file in Java with Examples

As we already discussed the file is like a container that stores information and can be used later. In this section, we will look at various methods to read files. In this tutorial, we assume that our file name, "MyFile.txt" contains the following data.

java read file!!
Welcome to golinuxclould!

Now let us apply different methods to read the existing file that contains the above data.

 

Method-1: Java read file using Java desktop class

The first method that we will use to read or open a file in java is the Desktop class. This class is present in the java.awt package. It has the method called open() that opens a file for us. As the Desktop is platform-independent, so we need to check whether our Operating System supports Desktop or not. If any error occurs, there arises an exception called FileNotFounDException.

Now let us take an example and open our file named "MyFile.txt". See the example below:

// importing desktop
import java.awt.Desktop;
// importing java io
import java.io. * ;
// main class
public class Main{
  public static void main(String[] args) {
    try {
      //constructor of file class  
       // java read file 
      File myFile = new File("Myfile.txt");
      // using if statment 
      if (!Desktop.isDesktopSupported())
      //check if Desktop is supported by Platform or not  
      {
        System.out.println("This is not supported by platform!");
        return;
      }
      Desktop desktop = Desktop.getDesktop();
      // checking if file exists or not
      if (myFile.exists())
      // Opens the file 
      desktop.open(myFile); 
    }
    // catch block to handle any kind of errors
    catch(Exception e) {
      System.out.println("Error accurs");
    }
  }
}

If we run the following code, It will open the file in the text editor as shown below:

Advertisement

Java read file using 5+ methods [Easy Examples]

This method can return different kinds of errors.

For example. NullPointer Exception if the file is null, IllegalArgumentException if the given file does not exist and UnsupportedOperationExecution if the platform does not support the Desktop. That is why it is always recommended to use try and catch blocks to handle any kind of exceptions.

You can read more about try and catch blocks from the article java try and catch blocks.

 

Method-2: Java read file using FileInputStream class

Another method to read files from a system using the java programming language isFileInputStream which reads input bytes from a file in a file system. Before using it, first, we have to import FileInputStream class. See the example below which uses this method to read the file.

// imporiting fileinputstream
import java.io.FileInputStream;  
// main class
public class Main {  
  // main method
    public static void main(String args[]){   
        //try block 
          try{    
            // constructor in fileinputstream class
           // java read file
            FileInputStream myfile=new FileInputStream("Myfile.txt");  
            // printing
            System.out.println("The file contains the followng data:");
            // counter
            int counter = 0;
            // while loop to iterate 
            while ((counter = myfile.read()) != -1) {
              System.out.print((char) counter);
            }  
          // catch block to hadle the error
          }catch(Exception e){
            System.out.println("Error accurs!");
          }    
         }    
        }

Output:

The file contains the following data:

java read file!!
Welcome to golinuxclould!

Notice that this method does not open the file in any other external software, In fact, it reads the data and prints out the data.

 

Method-3: Java read file using BufferedReader Class

Now let us take another method which is BufferedReader class. The BufferedReader class can also use to read and open a file in Java. It reads the text using a character input stream and is present in the java.io package. Let us take the example and see how we can read files. See the program below:

// importing io
import java.io. * ;
// main class
public class Main {
  // main method
  public static void main(String args[]) {
    try {
      //constructor of File class   
      // java read file
      File myfile = new File("Myfile.txt");
      //creates a buffer reader input stream 
      BufferedReader newfile = new BufferedReader(new FileReader(myfile));
      System.out.println("The file contains the following data: ");
      // counter
      int counter = 0;
      // while loop to iterate
      while ((counter = newfile.read()) != -1) {
        // java read file
        System.out.print((char) counter);
      }
    }
    catch(Exception e) {
      System.out.println("error occurs!");
    }
  }
}

Output:

Advertisement
The file contains the following data:

java read file!!
Welcome to golinuxclould!

Notice that this method prints all the data from the file using the while loop and iterating over the file unless it prints all the data in it. You can read more about the working principle of the while loop from the article Java while loop.

 

Method-4: Java read file using FileReader class

Another simple method to read a java file is using FileReader class, which is present in the java.io package. It reads bytes from FileInputStream class. Let us take an example and read a file and print out all the data. See the program below:

// importing io
import java.io. * ;
// main class
public class Main{
  // main method
  public static void main(String args[]) {
    // try block
    try {
      //constructor of the File class
      // Java read file
      FileReader myfile = new FileReader("Myfile.txt");
      // printing
      System.out.println("The file contains the following data: ");
      // counter
      int counter = 0;
      // while loop to iterate
      while ((counter = myfile.read()) != -1) {
        // java read file
        System.out.print((char) counter);   
      }
    }
    catch(Exception e) {
      System.out.println("Error occurs!!");
    }
  }
}

Output:

The file contains the following data:

java read file!!
Welcome to golinuxclould!

Notice that this method reads the file and then again uses the while loop to iterate over the data and prints out all.

 

Method-5: Java read file using Scanner class

The Scanner class of java.util package is also useful in reading and opening a file in Java. Java Scanner class can parse the text using regular expressions. It breaks the input on the delimiter’s pattern. By default the delimiter is whitespace, but we can also add our own delimiter. We use the constructor of the Scanner class for opening and reading a file. To understand the process more clearly, See the example below:

// importing file
import java.io.File;
// importing scanner
import java.util.Scanner;
// java main class
public class Main {
  // java main method
  public static void main(String[] args) {
    // try block
    try {
      // Stroing file 
      // java read file
      File file = new File("Myfile.txt");
      // File to be scanned
      Scanner myfile = new Scanner(file);
      System.out.println("The file contains the following data:");
      // while loop to iterate
      while (myfile.hasNextLine())
      //printing the data 
      System.out.println(myfile.nextLine());
    }
    catch(Exception e) {
      System.out.println("Error occurs!!");;
    }
  }
}

Output:

The file contains the following data:

java read file!!
Welcome to golinuxclould!

Notice that we successfully read and print the data from a file.

 

Method-6: Java read file using NIO package

The Java NIO package has many classes and methods that use to read and open a file in Java but here we will discuss readAllLines() method. The readAllLines() method is the method that belongs to the File class.

This method is widely used to read all the lines from a file and decode the bytes from the file into characters using UTF-8 charset. This method returns the lines from the file in the form of a list.

Now, let us take an example and read one file using this mehod. See the example below:

// importing util
import java.util. * ;
// importing standardCharsets
import java.nio.charset.StandardCharsets;
// importing file
import java.nio.file. * ;
// importing io
import java.io. * ;
// java main class
public class Main {
  // java readfile method
  // return type is list
  public static List < String > readFile(String fileName) {
    // create list using collections library
    List < String > lines = Collections.emptyList();
    // try block
    try {
      // java read file
      lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
    }
    // catch block to handle exception
    catch(IOException e) {
      System.out.println("Error occurs!");
    }
    // return lines of data
    return lines;
  }
// main method
  public static void main(String[] args) {
    System.out.println("The file containg the following data:");
    // java read file
    List mylist = readFile("Myfile.txt");
    // accessing the elements by calling the method
    Iterator < String > itr = mylist.iterator(); 
    // while loop to iterate
    while (itr.hasNext()) 
    // print
    System.out.println(itr.next()); 
  }
}

Output:

The file containg the following data:

java read file!!
Welcome to golinuxclould!

Notice that we successfully read the file and then print all the data using readAllLines() method.

 

Summary

A file is a container in a computer system that stores data, information, settings, or commands, which are used with a computer program. Files play important role in any programming language because they can store a large amount of data. We can create, write and read files in java using different methods. In this article, we learned about java read files by taking various methods.

For example, we learned about Desktop class, FileInputStream, BufferedReader, FileReader, Scanner, and readAllLines() methods by taking different examples. In a conclusion, this tutorial contains all the important methods and classes that are used to read java files.

 

Further Reading

Java read file

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment