Monday, September 2, 2024

4 ways to read String from File in Java - Example

Just like there are many ways for writing String to text file, there are multiple ways to read String form File in Java. You can use FileReader, BufferedReader, Scanner, and FileInputStream to read text from file. One thing to keep in mind is character encoding. You must use correct character encoding to read text file in Java, failing to do so will result in logically incorrect value, where you don't see any exception but content you have read is completely different than file's original content. Many of the method which is used to read String by default uses platform's default character encoding but they do have overloaded version which accepts character encoding. 


How to read String from a File in Java?

From Java 7 onwards you can even read a file as String in Java and that too in just one line. You are encouraged to use new File IO introduced in JDK 1.7, if you are running with Java 7 JVM. 

Now let's see examples of 4 different ways to read a String from file in Java.


1. Reading String from File using BufferedReader

Java provides a versatile set of tools for file I/O operations, and one common task is reading text data from a file. When it comes to reading strings from a file efficiently, the BufferedReader class is a handy choice. In this example, we will explore how to use BufferedReader to read a string from a file in Java.

To read a string from a file using BufferedReader in Java, you'll first need to import the necessary classes, including BufferedReader and FileReader. Then, create a BufferedReader object and open the file you want to read. Use a loop to read lines from the file using the readLine() method and append them to a StringBuilder to form a single string.

 After reading is complete, remember to close the BufferedReader to free up resources. Here's the complete Java program demonstrating these steps:

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;


public class ReadFileWithBufferedReader {

    public static void main(String[] args) {

        BufferedReader br = null;

        try {

            br = new BufferedReader(new FileReader("your_file.txt"));

            String line;

            StringBuilder stringBuilder = new StringBuilder();


            while ((line = br.readLine()) != null) {

                stringBuilder.append(line);

            }


            String fileContent = stringBuilder.toString();

            System.out.println("File content: ");

            System.out.println(fileContent);

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                if (br != null) {

                    br.close();

                }

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

}


java


2. Java 7 one liner to read String from text file

In Java 7 and later versions, you can simplify the process of reading a string from a text file using a one-liner of code, thanks to the Files and Charset classes. 

Here's how to do it:

import java.io.IOException;

import java.nio.charset.Charset;

import java.nio.file.Files;

import java.nio.file.Paths;


public class ReadFileWithJava7 {

    public static void main(String[] args) {

        String filePath = "your_file.txt"; // Replace with your file path

        try {

            String fileContent = new String(Files.readAllBytes(Paths.get(filePath)), Charset.defaultCharset());

            System.out.println("File content: ");

            System.out.println(fileContent);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

In this one-liner, we first specify the file path in the filePath variable (replace "your_file.txt" with the actual file path). Then, we use Files.readAllBytes() to read all the bytes from the file and convert them to a string using the default character encoding provided by Charset.defaultCharset(). Finally, we print the content of the file.

This approach simplifies file reading in Java 7 and is concise and efficient for reading text files into strings.

3. How to read String from file using Scanner

As I said before, the Java programming language offers various methods to read data from files, and one convenient option is to use the Scanner class. This class simplifies the process of reading strings from files. In this article, we will guide you through the steps to read a string from a file using the Scanner class.

To read a string from a file using the Scanner class in Java, follow these steps. First, import the necessary classes, including File, FileNotFoundException, and Scanner. Second, create a Scanner object and attach it to the file you want to read by providing the file's path as an argument. 

Third, use the Scanner object's nextLine() method to read the entire string from the file. Finally, close the Scanner to release system resources. Here's the complete Java program demonstrating these steps:

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;


public class ReadFileWithScanner {

    public static void main(String[] args) {

        String filePath = "your_file.txt"; // Replace with your file path

        Scanner scanner = null;


        try {

            scanner = new Scanner(new File(filePath));

            StringBuilder stringBuilder = new StringBuilder();


            while (scanner.hasNextLine()) {

                stringBuilder.append(scanner.nextLine());

            }


            String fileContent = stringBuilder.toString();

            System.out.println("File content: ");

            System.out.println(fileContent);

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } finally {

            if (scanner != null) {

                scanner.close();

            }

        }

    }

}

Replace "your_file.txt" with the actual path to the file you want to read. This program utilizes the Scanner class to efficiently read the file's contents into a string and then prints the content.


How to read String from File in Java - Example




4. How to read String from file using FileReader

To read a string from a file using the FileReader class in Java, follow these steps. First, import the necessary classes, including File, FileReader, and IOException. Second, create a FileReader object and specify the file you want to read by providing the file's path as an argument. 

Third, use a BufferedReader to read the file line by line and store the lines in a StringBuilder to form a single string. Finally, close the FileReader and BufferedReader to release system resources. Here's the complete Java program demonstrating these steps:

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;


public class ReadFileWithFileReader {

    public static void main(String[] args) {

        String filePath = "your_file.txt"; // Replace with your file path

        FileReader fileReader = null;

        BufferedReader bufferedReader = null;


        try {

            fileReader = new FileReader(new File(filePath));

            bufferedReader = new BufferedReader(fileReader);

            StringBuilder stringBuilder = new StringBuilder();

            String line;


            while ((line = bufferedReader.readLine()) != null) {

                stringBuilder.append(line);

            }


            String fileContent = stringBuilder.toString();

            System.out.println("File content: ");

            System.out.println(fileContent);

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                if (bufferedReader != null) {

                    bufferedReader.close();

                }

                if (fileReader != null) {

                    fileReader.close();

                }

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

}


That's all about how to read String from file in Java. Since text files are very common in programming world, you would always need this knowledge while working in Java. Though you can use this technique to read any kind of file in Java, you should better be using XML parsers to read XML file and HTML parsing library like Jsoup to read HTML files in Java.


Now quiz time, which one is your favorite way to read a File as String in Java? 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.