Java read files

Java read files

After creating and writing files in java, a user needs to know the concept of java read files. As we know to create a new file, we use createNewFile() method. The output is a Boolean value= true in case the file creation is successful. Otherwise, the program returns the output as false which means the file already exists. The system throws IOException if there is a problem in creation of the file. Similarly, to write a file, the user uses write() method. With the help of this method, the user can write() in the created file.

To read files in java, the use of scanner class comes into play. Scanner class will read the contents of the text file which exists already. In this, the scanner class breaks the input of the file into tokens. As a result, we get the output as the tokens into various types using methods such as nextLine(), hasnextLine() etc

For reading a file in Java and for doing file operations, we need to import some pre defined classes. We will require these classes:

java.io.File

java.io.FileNotFoundException

We will include these packages, and other necessary input-output packages in a single line using java.io.*.

Let’s see how to read a file in Java

Below is a program to illustrate how we can read in a file java using scanner class:

import java.io.File;
import java.io.FileNotFoundException;  
import java.util.Scanner; 
public class DeveloperHelps {
public static void main(String[] args) {
try {
File O = new File("filename.txt");
Scanner read = new Scanner(O);
while (read.hasNextLine()) {
String data = read.nextLine();
System.out.println(data);
    }
read.close();
    } 
catch (FileNotFoundException e) {
System.out.println("There is an error while reading the file");
e.printStackTrace();
    }
  }
}  


The output of this java program using scanner class will be:

There is an error while reading the file

The constructors that can be invoked for java read class are:
FileReader(String file): This constructor opens the file in the read mode and fetches filename in the string. The system throws an exception FileNotFound in case the user cannot find the file, or if the file is missing.

FileReader(File file): This will open the file in the read mode and fetches name of the file in the file instance. The system throws an exception FileNotFound in case the user cannot find the file, or if the file is missing.

Reading Java Text File Using BufferedReader()

The BufferedReader() class reads a character-input stream. It buffers characters in a buffer with a default size of 8 KB to make the reading process more efficient. If you want to read a file line by line, using BufferedReader is a good choice.

In this similar way to Scanner class, the user can also use BufferedReader to read the text of the file line by line. In this method, the user can read the text from character-input stream. The user performs the buffer process again and again for better and efficient results in reading characters or arrays. The syntax for BufferedReader to read a file is:

BufferedReader i= new BufferedReader(Reader i, int size);

Example Code 1 :

import java.io.*;  
public class DeveloperHelps{    
public static void main(String args[])throws Exception{             
    InputStreamReader x=new InputStreamReader(System.in);    
    BufferedReader br=new BufferedReader(x);            
    System.out.println("Apple is a fruit");    
    String name=br.readLine();    
    System.out.println("Cat is an animal");    
}    
} 


The output of this program will be:

Apple is a fruit
Cat is an animal

Example Code 2 :

import java.io.*;

public class FileReaderWithBufferedReader {

    public static void main(String[] args) throws IOException{We
        String file = "src/file.txt";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

        String apple;
        while ((curLine = bufferedReader.readLine()) != null){
            //process the line as required
            System.out.println(apple);
        }
        bufferedReader.close();
    }
}


Output :

apple

Reading Large Files :

If you want to read a large file with the Files class, you can use the newBufferedReader() method to obtain an instance of BufferedReader class and read the file line by line using a BufferedReader

import java.io.*;
import java.nio.file.*;

public class LargeFileReaderWithFiles {

    public static void main(String[] args) throws IOException {
        String file = "src/file.txt";
        Path path = Paths.get(file);
        BufferedReader bufferedReader = Files.newBufferedReader(path);

        String curLine;
        while ((curLine = bufferedReader.readLine()) != null){
            System.out.println(curLine);
        }
        bufferedReader.close();
    }
}


Reading File using Files.lines()

Files class was introduced in Java 8. It converts the whole file to a Stream of strings.

Files.lines() help us to reading text from file Java, line by line. Files.lines() closes the opened resources automatically (ie, the file), so we do not need to close the file, and we can skip try and catch blocks for Files.lines().

For using Files.lines(), we will need to define the path of the file. We can use the Paths.get() function Path library. For using this function, we need to include the java.nio.file. package*. For using the Stream functions, we need to include java.util.stream.* package

Example Code :

import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
class Files_Lines2
{
   public static void main() throws IOException
   {
       String str = "C:\\Bhavya\\Scaler\\readThisFile.txt";
       Path dir = Paths.get(str);                                // Defining the path to the file.
       Stream<String> content = Files.lines(dir);                // Storing the data of the file.
       List<String> data = content.collect(Collectors.toList()); // storing the data in a list
       for (String i : data)
       {
           System.out.println(i); // printing the list
       }
   }
}


Output :

The quick brown fox
jumps over the lazy dog.

Java has launched a new version Java SE 8 in which there’s an introduction to new class for more efficient reading of file. It is java.util.stream.Stream. There is one more way of reading file content in java. We can do it using FileReader class. This class is the best one when the user wants to read character files. When the constructor of the class is invoked, it presumes that default character encoding is appropriate.   

The user can also read files in java by reading all the lines of the file in a list. The method ensures that the file will get closed when all the content is read. The bytes of the file are decoded using a particular char set.  The output is in the form of DataInputStream class.

After following the processes such as create a file, write a file, read a file, the last method which is followed is delete a file. The user can do this by using delete() method. This method deletes all the contents of the file.

Leave a comment

Your email address will not be published. Required fields are marked *

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Java Online Quiz

Level up your coding skills with our interactive programming quiz!