Skip to content

Latest commit

 

History

History
86 lines (58 loc) · 2.66 KB

File metadata and controls

86 lines (58 loc) · 2.66 KB

Java 程序:将文本附加到现有文件

原文: https://www.programiz.com/java-programming/examples/append-text-existing-file

在此程序中,您将学习将 Java 文本附加到现有文件的各种技巧。

在将文本附加到现有文件之前,我们假设在src文件夹中有一个名为test.txt的文件。

这是test.txt的内容

This is a
Test file.

示例 1:将文本附加到现有文件

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class AppendFile {

    public static void main(String[] args) {

        String path = System.getProperty("user.dir") + "\\src\\test.txt";
        String text = "Added text";

        try {
            Files.write(Paths.get(path), text.getBytes(), StandardOpenOption.APPEND);
        } catch (IOException e) {
        }
    }
}

运行该程序时,test.txt文件现在包含:

This is a
Test file.Added text

在上面的程序中,我们使用Systemuser.dir属性获取存储在变量path中的当前目录。 检查 Java 程序:获取当前目录,以获取更多信息。

同样,要添加的文本存储在变量text中。 然后,在try-catch块内,我们使用Fileswrite()方法将文本附加到现有文件中。

write()方法采用给定文件的路径,要写入的文本以及应如何打开文件进行写入。 在我们的例子中,我们使用APPEND选项进行写入。

由于write()方法可能返回IOException,因此我们使用try-catch块来正确捕获异常。


示例 2:使用FileWriter将文本附加到现有文件

import java.io.FileWriter;
import java.io.IOException;

public class AppendFile {

    public static void main(String[] args) {

        String path = System.getProperty("user.dir") + "\\src\\test.txt";
        String text = "Added text";

        try {
            FileWriter fw = new FileWriter(path, true);
            fw.write(text);
            fw.close();
        }
        catch(IOException e) {
        }
    }
}

该程序的输出与示例 1 相同。

在上述程序中,不是使用write()方法,而是使用FileWriter的实例(对象)将文本附加到现有文件中。

创建FileWriter对象时,我们传递文件的路径,并以true作为第二个参数。true表示我们允许添加文件。

然后,我们使用write()方法附加给定的text并关闭文件写入器。