Whole text file to a String in Java

Whole text file to a String in Java

You can read the contents of a whole text file into a String in Java using several methods. Below are two common approaches using Java's standard libraries.

Method 1: Using FileReader and BufferedReader (Java 7 and later)

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadFileToString { public static void main(String[] args) { String filePath = "yourfile.txt"; // Replace with the path to your text file try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line).append('\n'); } String fileContent = stringBuilder.toString(); System.out.println(fileContent); } catch (IOException e) { e.printStackTrace(); } } } 

In this code:

  • We create a BufferedReader to efficiently read the text file line by line.
  • We use a StringBuilder to accumulate the lines and form the final String.

Method 2: Using Files.readAllBytes and StandardCharsets (Java 8 and later)

import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; public class ReadFileToStringJava8 { public static void main(String[] args) { String filePath = "yourfile.txt"; // Replace with the path to your text file try { byte[] bytes = Files.readAllBytes(Paths.get(filePath)); String fileContent = new String(bytes, StandardCharsets.UTF_8); System.out.println(fileContent); } catch (IOException e) { e.printStackTrace(); } } } 

In this code:

  • We use Files.readAllBytes to read all the bytes from the file.
  • We specify the character encoding using StandardCharsets.UTF_8.
  • We create a String from the byte array to get the file's content as a String.

Replace "yourfile.txt" with the actual path to your text file. Make sure to handle potential IOExceptions that may occur during file reading.


More Tags

jackson-dataformat-xml dfa sharepoint-2013 persian fullcalendar-4 definition modulo area deviceid activity-indicator

More Java Questions

More Other animals Calculators

More Statistics Calculators

More Various Measurements Units Calculators

More Investment Calculators