DEV Community

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

Posted on

3

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay