跳到主要内容

Java 程序:从文件内容创建字符串

要理解此示例,您应该具备以下 Java 编程 主题的知识:

在我们从文件创建字符串之前,我们假设在我们的 src 文件夹中有一个名为 test.txt 的文件。

以下是 test.txt 的内容

This is a
Test file.

示例 1:从文件创建字符串

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);
}
}

输出

[This is a, Test file.]

在上述程序中,我们使用 Systemuser.dir 属性来获取当前目录,存储在变量 path 中。更多信息请查看 Java 程序获取当前目录

我们使用了 defaultCharset() 作为文件的编码。如果您知道编码,请使用它;否则,使用默认编码是安全的。

然后,我们使用了 readAllLines() 方法从文件中读取所有行。它接受文件的 path 和其 encoding,并返回所有行的列表,如输出所示。

由于 readAllLines 可能也会抛出 IOException,我们必须这样定义我们的 main 方法:

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

示例 2:从文件创建字符串

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);
}
}

输出

This is a
Test file.

在上述程序中,我们获取的不是字符串列表,而是包含所有内容的单个字符串 lines

为此,我们使用了 readAllBytes() 方法从给定路径读取所有字节。这些字节然后使用默认的 encoding 转换为字符串。