DEV Community

Tip Season
Tip Season

Posted on • Edited on • Originally published at tipseason.com

5 2

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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (1)

Collapse
 
kaviiiiisha profile image
Kavisha Nethmini

Thanks for the tip :)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay