How to Read a File to String

JavaJavaBeginner
Practice Now

Introduction

Storing data into a file is useful for permanent storage. In Java, there are four classes that can be used to read files: FileReader, Scanner, FileInputStream, and BufferedReader. These classes are part of the java.io package, and are used for file handling in Java.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/FileandIOManagementGroup(["`File and I/O Management`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("`Exceptions`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/user_input("`User Input`") java/FileandIOManagementGroup -.-> java/files("`Files`") java/FileandIOManagementGroup -.-> java/read_files("`Read Files`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/StringManipulationGroup -.-> java/stringbuffer_stringbuilder("`StringBuffer/StringBuilder`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/type_casting("`Type Casting`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/BasicSyntaxGroup -.-> java/while_loop("`While Loop`") java/SystemandDataProcessingGroup -.-> java/object_methods("`Object Methods`") java/SystemandDataProcessingGroup -.-> java/string_methods("`String Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117443{{"`How to Read a File to String`"}} java/exceptions -.-> lab-117443{{"`How to Read a File to String`"}} java/oop -.-> lab-117443{{"`How to Read a File to String`"}} java/user_input -.-> lab-117443{{"`How to Read a File to String`"}} java/files -.-> lab-117443{{"`How to Read a File to String`"}} java/read_files -.-> lab-117443{{"`How to Read a File to String`"}} java/identifier -.-> lab-117443{{"`How to Read a File to String`"}} java/stringbuffer_stringbuilder -.-> lab-117443{{"`How to Read a File to String`"}} java/arrays -.-> lab-117443{{"`How to Read a File to String`"}} java/comments -.-> lab-117443{{"`How to Read a File to String`"}} java/data_types -.-> lab-117443{{"`How to Read a File to String`"}} java/operators -.-> lab-117443{{"`How to Read a File to String`"}} java/output -.-> lab-117443{{"`How to Read a File to String`"}} java/strings -.-> lab-117443{{"`How to Read a File to String`"}} java/type_casting -.-> lab-117443{{"`How to Read a File to String`"}} java/variables -.-> lab-117443{{"`How to Read a File to String`"}} java/while_loop -.-> lab-117443{{"`How to Read a File to String`"}} java/object_methods -.-> lab-117443{{"`How to Read a File to String`"}} java/string_methods -.-> lab-117443{{"`How to Read a File to String`"}} java/system_methods -.-> lab-117443{{"`How to Read a File to String`"}} end

Create a Sample File

Start by creating a sample .txt file to read. You can use any text editor to create this file, and it can contain any data that you'd like to read. Example:

This is the sample data stored in a file
Rahul:10025
Sohan:10026
Madan:10027
Jack:10028

Import Required Classes

In order to read the file and convert its contents to a string, you will need to import the following classes:

import java.io.*;

Reading a File with FileReader

Use the FileReader class to read data from the file. An object of FileReader class points to the beginning of a file. Use a buffer of size 1 to read each character of the file, and append it to a String variable.

try {
     // Step 1: Create a new FileReader object
     FileReader fr = new FileReader("path/to/your/file.txt");

     // Step 2: Create a String variable to hold the contents of the file
     String fileData = "";

     // Step 3: Create an integer variable to hold each character read
     int c;

     // Step 4: Keep reading the file until the end of the file has been reached
     while ((c = fr.read()) != -1) {

         // Step 5: Append each character read to the fileData string
         fileData += (char) c;
     }

     // Step 6: Print the contents of the file
     System.out.println(fileData);

     // Step 7: Close the file reader
     fr.close();

 } catch (IOException e) {
     e.printStackTrace();
 }

Reading a File with Scanner

Use the Scanner class to read data from a text file. You need to provide the text file as an input source to the scanner, then delimit the scanner with \\Z method to read the whole data at once and converts it into a String.

try {
     File file = new File("path/to/file.txt");
     Scanner scanner = new Scanner(file);

     scanner.useDelimiter("\\Z");

     String fileData = scanner.next();
     System.out.println(fileData);

     scanner.close();
 } catch (FileNotFoundException e) {
     e.printStackTrace();
 }

Reading a File with FileInputStream

Use the FileInputStream class to read data directly from the file into a byte array. Create a buffer of your desired size (10 bytes in our example) to temporarily store data read from the file, then append it to a StringBuilder object. Finally, we use the toString() method to convert the contents of the StringBuilder object to a String.

try {
     File file = new File("path/to/file.txt");
     FileInputStream fileInputStream = new FileInputStream(file);
     byte[] buffer = new byte[10];
     StringBuilder stringBuilder = new StringBuilder();

     int length;
     while ((length = fileInputStream.read(buffer)) != -1) {
         stringBuilder.append(new String(buffer, 0, length));
     }

     String fileData = stringBuilder.toString();
     System.out.println(fileData);

     fileInputStream.close();

 } catch (IOException e) {
     e.printStackTrace();
 }

Reading a File with BufferedReader

Use the BufferedReader class to read data from a file in a simple way. It will read all the data at once, and you can then print it line by line using the readLine() method.

try {
     File file = new File("path/to/file.txt");
     BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
     String line;

     while ((line = bufferedReader.readLine()) != null) {
         System.out.println(line);
     }

     bufferedReader.close();

 } catch (IOException e) {
     e.printStackTrace();
 }

Summary

In this lab, you have learned how to read data from a file to a String in Java. There are multiple ways of achieving this, including using FileReader, Scanner, FileInputStream, and BufferedReader classes. We recommend experimenting with these methods yourself, in order to understand how they work and which is the most appropriate for your specific use case. Remember to test your code and verify the path to your text file.

Other Java Tutorials you may like