Ticker

6/recent/ticker-posts

Ad Code

Responsive Advertisement

In Java How to Read a File and Convert File to String? (5 different ways)

In Java How to Read a File and Convert File to String? (5 different ways)

What is simplest way to read a file into String? Do you want to read a plain text file in Java? How do you want to convert a File object to a String object? There are multiple ways we can read a file and covert it to String.

There are 5 total ways to convert whole text file to a String in Java.

  1. Files.readString()
  2. Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
  3. FileUtils.readFileToString(new File(path), StandardCharsets.UTF_8); – Apache Commons IO Dependency
  4. Files.lines()
  5. Files.newBufferedReader()

Let’s get started:

<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
  • Create class CrunchifyConvertFileToString.java.
  • Copy and paste below code into it.

CrunchifyConvertFileToString.java

package crunchify.com.java.tutorials;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * @author Crunchify.com
 * Program: In Java How to Read a File and Convert File to String? (5 different ways)
 */

public class CrunchifyConvertFileToString {
    public static void main(String[] args) {

        // Files.readString()
        crunchifyFilesReadString();

        // Files.readAllLines(Paths.get();
        crunchifyFilesReadAllLines();

        // FileUtils.readFileToString(new File();
        // Apache Commons IO method
        crunchifyFileUtilsReadFileToString();

        // Files.lines()
        // Please visit: https://crunchify.me/3CDrP7N
        crunchifyFilesLines();

        // Files.newBufferedReader()
        // Please visit: https://crunchify.me/3CDrP7N
        crunchifyFilesNewBufferedReader();

    }


    /*
    Method-1: Files.readString()
     */
    private static void crunchifyFilesReadString() {
        String crunchifyFilePath = "/Users/app/Downloads/crunchify-file-to-string.txt";

        try {
            crunchifyLog("\n================= Files.readString() =================");

            // Files: This class consists exclusively of static methods that operate on files, directories, or other types of files.
            // Paths: This class consists exclusively of static methods that return a Path by converting a path string or URI.
            // get(): Converts a path string, or a sequence of strings that when joined form a path string, to a Path.

            String crunchifyFileData = Files.readString(Paths.get(crunchifyFilePath));

            crunchifyLog(crunchifyFileData);

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

    /*
    Simple Logging Utility
     */
    private static void crunchifyLog(Object crunchifyFileData) {

        System.out.println(crunchifyFileData);
    }

    /*
    Method-2: Files.readAllLines(Paths.get();
     */
    private static void crunchifyFilesReadAllLines() {

        crunchifyLog("================= Files.readAllLines() =================");

        String crunchifyFilePath = "/Users/app/Downloads/crunchify-file-to-string.txt";

        try {

            // readAllLines(): Read all lines from a file. This method ensures that the file is closed when
            // all bytes have been read or an I/O error, or other runtime exception, is thrown.
            // Bytes from the file are decoded into characters using the specified charset.

            // This method recognizes the following as line terminators:

            /*  \u000D followed by \u000A, CARRIAGE RETURN followed by LINE FEED
                \u000A, LINE FEED
                \u000D, CARRIAGE RETURN
            */

            List<String> crunchifyFileData = Files.readAllLines(Paths.get(crunchifyFilePath), StandardCharsets.UTF_8);

            crunchifyLog(crunchifyFileData);

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

    }

    /*
    Method-3: FileUtils.readFileToString(new File();
    Apache Commons IO:  <dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.6</version></dependency>
     */
    private static void crunchifyFileUtilsReadFileToString() {

        crunchifyLog("\n================= FileUtils.readFileToString() =================");

        String crunchifyFilePath = "/Users/app/Downloads/crunchify-file-to-string.txt";

        try {

            // readFileToString: Reads the contents of a file into a String. The file is always closed.
            String crunchifyFileData = FileUtils.readFileToString(new File(crunchifyFilePath), StandardCharsets.UTF_8);
            // UTF_8: Eight-bit UCS Transformation Format.

            crunchifyLog(crunchifyFileData);
        } catch (IOException exception) {
            exception.printStackTrace();
        }

    }

    /*
    Method-4: Files.lines()
    */
    private static void crunchifyFilesLines() {

        // Please visit: https://crunchify.me/3CDrP7N
    }

    /*
    Method-5: Files.newBufferedReader()
    */
    private static void crunchifyFilesNewBufferedReader() {

        // Please visit: https://crunchify.me/3CDrP7N
    }

}

IntelliJ IDEA Console Result:

Just run above program as a Java Application you will see result as below.

================= Files.readString() =================
Five Ways to Read File and Convert it to String :)

Files.readString()
Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
FileUtils.readFileToString(new File(path), StandardCharsets.UTF_8);
Files.lines()
Files.newBufferedReader()

================= Files.readAllLines() =================
[Five Ways to Read File and Convert it to String :), , Files.readString(), Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);, FileUtils.readFileToString(new File(path), StandardCharsets.UTF_8);, Files.lines(), Files.newBufferedReader()]

================= FileUtils.readFileToString() =================
Five Ways to Read File and Convert it to String :)

Files.readString()
Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
FileUtils.readFileToString(new File(path), StandardCharsets.UTF_8);
Files.lines()
Files.newBufferedReader()


Process finished with exit code 0

Let me know if you face any issue running above code.

Here a tutorial which explains method4 and method-5:

The post In Java How to Read a File and Convert File to String? (5 different ways) appeared first on Crunchify.

Enregistrer un commentaire

0 Commentaires