---
title: Create string from contents of a file
url: https://docs.vultr.com/java/examples/create-string-from-contents-of-a-file
publish_date: 2024-11-26T15:40:00.067144Z
last_updated: 2024-11-26T15:40:00.067144Z
header_image: https://docs.vultr.com/public/doc-assets/collection-items/1062/0800e141-5f83-4ce4-b256-22585dd69d4b.jpg
---

> Index of every Vultr Docs page in markdown: https://docs.vultr.com/llms.txt

# Java Program to Create String from Contents of a File

## Introduction
Creating a string from the contents of a file is a common operation in Java programming, often required when dealing with text processing or when configuration data is stored in files. Using Java's I/O classes allows you to efficiently read and transform file data into strings for further manipulation or analysis.

In this article, you will learn how to develop a Java program that can read the contents of a file and convert them into a string. Implement several methods using both old and new I/O libraries provided by Java for handling file operations.

## Using BufferedReader and FileReader
These two classes constitute one of the traditional methods to read files in Java. `BufferedReader` reads text from a character-input stream, buffering characters to provide efficient reading of characters, arrays, and lines. The `FileReader` is convenient for reading streams of characters.

### Read a File into a String
1. Import necessary classes.
1. Create a `BufferedReader` object using `FileReader`.
1. Read the file line by line and append it to `StringBuilder`.
1. Convert `StringBuilder` to string.

    ```java
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;

    public class FileToString {
        public static void main(String[] args) {
            String filePath = "example.txt"; // The file path
            StringBuilder contentBuilder = new StringBuilder();

            try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    contentBuilder.append(line).append(System.lineSeparator());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            String fileContent = contentBuilder.toString();
            System.out.println(fileContent);
        }
    }
    ```

    This code snippet opens the file located at `example.txt` and reads through it using `BufferedReader`. Each line is appended to a `StringBuilder`, and each line terminates with a system-dependent line separator to maintain the formatting. The resulting string is then outputted to the console.

## Using Java NIO File Class
Java NIO (New Input/Output) provides a different approach for handling I/O operations, offering a more scalable option when working with files.

### Utilize Files and Paths Classes
1. Import NIO classes.
1. Use `Files.readAllBytes` to read file contents.
1. Convert byte array to string using the file's original encoding.

    ```java
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.nio.charset.StandardCharsets;

    public class FileToStringNIO {
        public static void main(String[] args) {
            String filePath = "example.txt"; // The file path

            try {
                String content = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
                System.out.println(content);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    ```

    This example uses the Java NIO `Files` class to read all bytes from the file `example.txt` into a byte array, which is then converted into a `String`. The `StandardCharsets.UTF_8` ensures that the bytes are decoded correctly according to the UTF-8 charset.

## Conclusion
Extracting the contents of a file into a string in Java can be achieved using various methods, depending on the specific requirements and the size of the file to be processed. The traditional I/O approach with `BufferedReader` and `FileReader` is straightforward and suitable for line-by-line processing. For larger files or more modern applications, Java NIO provides efficient and scalable solutions. Utilize these examples as a basis for integrating file reading operations into Java applications, ensuring smooth handling of file data.