Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

read
file
string
java

How to read a file to string in Java

Educative Answers Team

Dealing with files in Java involves frequently performing operations like reading the file, converting to a string, etc.

svg viewer

Using BufferedReader class

In the code below my_Reader, the object of BufferedReader class, is used to read the file. The object of StringBuilder is used to append the content to a string after reading it from the file.

main.java
data.txt
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class BufferedReaderExample {

	public static void main(String[] args) {

		try {
			
			BufferedReader my_Reader = new BufferedReader(new FileReader(new File(
					"data.txt")));
			String line = "";
      			StringBuilder str = new StringBuilder();
			while((line = my_Reader.readLine()) != null)
			{
        str.append(line);
			}
      System.out.println(str);
			my_Reader.close();
		} catch (FileNotFoundException e) {
			System.out.println("File not exists or insufficient rights");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("An exception occured while reading the file");
			e.printStackTrace();
		}

	}

}

RELATED TAGS

read
file
string
java
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring