5 simple ways to convert file to a string in java + bonus tech tip

5 simple ways to convert file to a string in java + bonus tech tip

Java tips to bookmark and share

ยท

2 min read

Writing real world application code in java involves file and string processing. Some of the common use cases to convert a file to string are as follows.

  1. Read a JSON file and parse content from it.
  2. Read a CSV file for machine learning input data.

There are numerous other use cases for this. So given the huge number of applications, in this tutorial we will discuss 5 simple and handpicked ways to read or convert a file into a String in Java. Depending upon your project configuration, you can use any of the following methods.

1. Using Java 1.11+ 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);

This method works with Java 1.11+

2. Using Java 1.8+ inbuilt Streams package:

String result = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);

This method works with Java 1.8+

3. Native Java Scanner way:

try (Scanner scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name())) {
    String result = scanner.useDelimiter("\\A").next();   
}

Note that "\A" represents regex pattern for useDelimiter scanner method. "\A" stands for :start of a string! . So when this pattern is supplied, whole stream is ready into the scanner object.

4. Apache commons-io IOUtils way:

File file = new File("data.txt");
String result = FileUtils.readFileToString(file, StandardCharsets.UTF_8);

For this method, Apache commons-io library should be included into your project. You can include it with this maven link

5. Using Google Guava library:

String result = Files.toString(new File(path), Charsets.UTF_8);

For this method, Guava library should be included into your project. You can include it with this maven link

If you want to play around with actual InputStreams without any utility methods you can use the above style.

What's next: How to read or convert an inputstream into a string in java

We have started a coding community for most frequently used real world coding tips. You can join us here

TipSeason Facebook Group: TipSeason Facebook Group

TipSeason Discord channel: TipSeason Discord channel

If you feel there are any other better ways to convert the streams or if you have any questions please comment below.

As a bonus here is a simple tech tip to increase your productivity.

Did you find this article valuable?

Support Tip Season by becoming a sponsor. Any amount is appreciated!

ย