English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input/Output (I/O)/O)

Java Reader/Writer

Java Other Topics

Java program creates strings based on file content

Comprehensive Java Examples

In this program, you will learn different techniques to create strings from the content of a given file using Java.

Before creating a string from the file, we assume that insrcThere is a folder namedtest.txtfile.

This istest.txtcontent

This is a
Test file.

Example1Create string from file

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class FileString {
    public static void main(String[] args) throws IOException {
        String path = System.getProperty("user.dir") + "\\src\\test.txt";
        Charset encoding = Charset.defaultCharset();
        List<String> lines = Files.readAllLines(Paths.get(path), encoding);
        System.out.println(lines);
    }
}

When running this program, the output is:

[This is a, Test file.]

In the above program, we use the user.dir property of System to get the current directory path stored in the variable. CheckJava program to get the current directory to getMore information.

We use defaultCharset() as the file encoding. If you know the encoding, please use it; otherwise, using the default encoding is safe

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

Since readAllLines may also throw IOException, we must define the main method in this way

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

Example2Create string from file

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileString {
    public static void main(String[] args) throws IOException {
        String path = System.getProperty("user.dir") + "\\src\\test.txt";
        Charset encoding = Charset.defaultCharset();
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        String lines = new String(encoded, encoding);
        System.out.println(lines);
    }
}

When running this program, the output is:

This is a
Test file.

In the above program, we do not get a list of strings, but a single string containing all the content.

For this, we use the readAllBytes() method to read all bytes from the given path. Then we convert these bytes to a string using the default encoding.

Comprehensive Java Examples