In these examples, we take a look at how to convert a file to String in various Java versions.
Example 1: Java 7 or belowpackage 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!
More Posts related to Java,
- Convert Java Map Collection Object to JSON String using Jackson
- Java Stream flatmap() Examples
- [Fix] Instant java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Years
- How to run Java Unit Test cases with Apache Maven?
- How to check if Java main thread is alive
- [Fix] java: incompatible types: incompatible parameter types in lambda expression error
- Parsing CSV file using Java code example (Comma Separated File)
- Unhandled exception type InterruptedException : Java Threads
- Native getClass() method from java.lang.Object Class Explained with examples.
- Java Jackson ObjectMapper Class with Examples
- Java 8 Streams map() with examples
- Java 8 - Convert List to Map Examples
- IntelliJ: Error: Could not find or load main class, java.lang.ClassNotFoundException
- Java Stream with Multiple Filters Example
- How to Clear StringJoiner in Java 8
- Spring 5 IoC Example with application Context XML (ClassPathXmlApplicationContext) and Gradle.
- How to get end of line (EOL) or new line character \r \n in Java
- Spring Boot CRUD Examples using JDBCTemplate
- Delete a File in Java with Examples
- Implementing Insertion Sort Algorithm in Java Program
- Java JDBC Batch Update Example with PreparedStatement
- Java JDBC Select Multiple Records from table as List using PreparedStatement
- [Hibernate] The method buildSessionFactory() from the type Configuration is deprecated
- How to fix Java HTTP java.net.UnknownHostException
- Java 8 Display time in 12 hour AM PM format
More Posts:
- How to remove Extra Spaces in Notepad++ - NotepadPlusPlus
- Two Ways to Extract rar (*.rar) files on Mac - MacOS
- Java Multi-line String Example - Java
- Java 8 Leap year check using Year class from java.time api - Java
- Microsoft Lists and SharePoint Online edit grid view - use undo and redo changes - SharePoint
- How to get SharePoint List Item URL using PowerShell - SharePoint
- Docker Commit Command with Examples - Docker
- How to get Java Thread name Example [Program] - Java