Java: How to convert a file to String


In these examples, we take a look at how to convert a file to String in various Java versions.

Example 1: Java 7 or below
package org.code2care.java.examples;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Java7FileToStringExample {

    public static void main(String[] args) {

        File textFile = new File("c:/data/myfile.txt");

        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(textFile))) {

            StringBuilder stringBuilder = new StringBuilder();
            String line;

            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
                stringBuilder.append(System.lineSeparator());
            }

            String fileToString = stringBuilder.toString();

            System.out.println(fileToString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Example 2: Java 8 or above

You can make use of the improved Java 8 Files class to make you code look more cleaner and shorter to perform the same operation.

package org.code2care.java.examples;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Java8FileToStringExample {
    
    public static void main(String[] args) throws IOException {

        Path txtFilePath = Path.of("c:/data/myfile.txt");
        String fileToString = new String(Files.readAllBytes(txtFilePath));

        System.out.println(fileToString);

    }
}

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap