Java Program to Create String from Contents of a File

In this program, you’ll learn different techniques to create a string from concents of a given file in Java.

Before we create a string from a file, we assume we have a file named test.txt in our src folder.

Here’s the content of test.txt

This is a
Test file.

Example 1: Create String from file

  1. import java.io.IOException;
  2. import java.nio.charset.Charset;
  3. import java.nio.charset.StandardCharsets;
  4. import java.nio.file.Files;
  5. import java.nio.file.Paths;
  6. import java.util.List;
  7. public class FileString {
  8. public static void main(String[] args) throws IOException {
  9. String path = System.getProperty("user.dir") + "\\src\\test.txt";
  10. Charset encoding = Charset.defaultCharset();
  11. List<String> lines = Files.readAllLines(Paths.get(path), encoding);
  12. System.out.println(lines);
  13. }
  14. }

When you run the program, the output will be:

[This is a, Test file.]

In the above program, we use System‘s user.dir property to get the current directory stored in the variable path.

We used defaultCharset() for the file’s encoding. If you know the encoding, use it, else it’s safe to use default encoding.

Then, we used readAllLines() method to read all lines from the file. It takes path of the file and its encoding, and returns all the lines as a list as shown in the output.

Since, readAllLines may also throw an IOException, we have to define our main method as such

public static void main(String[] args) throws IOException

Example 2: Create string from a file

  1. import java.io.IOException;
  2. import java.nio.charset.Charset;
  3. import java.nio.file.Files;
  4. import java.nio.file.Paths;
  5. public class FileString {
  6. public static void main(String[] args) throws IOException {
  7. String path = System.getProperty("user.dir") + "\\src\\test.txt";
  8. Charset encoding = Charset.defaultCharset();
  9. byte[] encoded = Files.readAllBytes(Paths.get(path));
  10. String lines = new String(encoded, encoding);
  11. System.out.println(lines);
  12. }
  13. }

When you run the program, the output will be:

This is a
Test file.

In the above program, instead of getting a list of string, we get a single string, lines, with all the contents.

For this, we used readAllBytes() method to read all bytes from the given path. These bytes are then converted to a string using the default encoding.