How to convert file to string in native java ?

tipseason

Tip Season

Posted on June 11, 2022

How to convert file to string in native java ?

Writing real world java code and some of the java interviews involves file and string processing. One of the common use cases is to convert a file to string. For eg: Read a json file and parse content from it.

There are numerous ways to convert file to string in java. Let's talk about the most frequently used ones.

1. If you are using Java 1.11+ , you can use inbuilt Files package:
import java.nio.file.Files;
import java.nio.file.Path;

String result = Files.readString(Path.of("filePath"));

//To Write string to a file you can use 
String content = "Demo Content";
Files.writeString(filePath, content);
Enter fullscreen mode Exit fullscreen mode
2. If you are using Java 1.8+ inbuilt Streams package:
String result = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
Enter fullscreen mode Exit fullscreen mode

This method works with Java 1.8+

There are few more ways to convert using scanner class, Google Guava library, Apache commons library. You can see them in here.
How to read and write to file as a string in java in simple way

Bonus: How to read or convert an inputstream into a string in java

💖 💪 🙅 🚩
tipseason
Tip Season

Posted on June 11, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related