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

教程基础Java

Contrôle de flux Java

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

traitement exception Java

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

Java程序将文本追加到现有文件

Comprehensive list of Java examples

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

在将文本追加到现有文件之前,我们假设在srcDossier d'un nomtest.txt的文件。

这是test.txt的内容

This is a
Test file.

Exemple1:将文本追加到现有文件

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

Lors de l'exécution du programme,test.txtLe fichier contient maintenant :

This is a
Test file.Added text

Dans le programme ci-dessus, nous utilisons l'attribut user.dir du système pour obtenir le chemin d'accès actuel stocké dans la variable path. VérifiezJava程序以获取当前目录以获取Plus d'informations.

De même, le texte à ajouter est également stocké dans la variable text. Ensuite, dans un try-catch块内,我们使用Files的write()方法将文本追加到现有文件中。

La méthode write() utilise le chemin d'accès au fichier donné, le texte à écrire dans le fichier et comment ouvrir le fichier pour l'écriture. Dans notre exemple, nous utilisons l'option APPEND pour l'écriture

En raison du fait que la méthode write() peut renvoyer IOException, nous utilisons un try-catch块来正确捕获异常。

Exemple2:Utilisez FileWriter pour ajouter du texte à un fichier existant

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

The output of the program is the same as the example1The same.

In the above program, we use an instance (object) of FileWriter instead of the write() method to append text to an existing file

When creating the FileWriter object, we pass the file path and set true as the second parameter. True indicates that we allow file appending

Then, we use the write() method to append the given text and close the file writer

Comprehensive list of Java examples