DEV Community

Cover image for Trick to read all the content of a file in java
Debojyoti Chakraborty
Debojyoti Chakraborty

Posted on

Trick to read all the content of a file in java

Hello I recently need to write a program where I need to find the duplicates book title from a given text file and store it in a output file.

But it's quite difficult to read file in java as there are many options available but after searching the internet I found the awesome process where you can read the file just with few lines of code.

Let's see the code

//required imports
//such as file handling java.io //and java.files
import java.io.*;
import java.util.Iterator;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;


//utility class for read the file in line and store it in
//an array and return it.
class OpenFileExample6 {
    //functions static to call from outside to the class
    public static List<String> readFileInList(String fileName) {

        //craeted a list of strings to store all the title from the file

        List<String> lines = Collections.emptyList();

        //required try catch block to avoid any Input Output Exception and program can run
        //without any error
        try {
            lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //return the string of array
        return lines;
    }
}
Enter fullscreen mode Exit fullscreen mode

Above code I used to read all the content from the file the magic is happened by these lines

try {
            lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
Enter fullscreen mode Exit fullscreen mode

Great now it's your turn to use it in java to read the file and don't forget to import java.nio library.

Top comments (0)