Java教程

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

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

在本程序中,您将学习不同的技术,以在 Java 中根据给定文件的内容创建字符串。
要理解此示例,您应该了解以下Java 编程主题:
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 Program to get the current directory了解更多信息。
我们使用 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 将这些字节转换为字符串。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4