Comment écrire dans un fichier en Java - BufferedWriter

Comment écrire dans un fichier en Java - BufferedWriter

En Java, nous pouvons utiliserBufferedWriter pour écrire du contenu dans un fichier.

    // jdk 7
    try (FileWriter writer = new FileWriter("app.log");
         BufferedWriter bw = new BufferedWriter(writer)) {

        bw.write(content);

    } catch (IOException e) {
        System.err.format("IOException: %s%n", e);
    }

Note
Si possible, utiliseFiles.write à la place, une ligne, simple et agréable.

    List list = Arrays.asList("Line 1", "Line 2");
    Files.write(Paths.get("app.log"), list);

1. BufferedWriter

Écrivez le contenu dans un fichier.

FileExample1.java

package com.example;

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

public class FileExample1 {

    public static void main(String[] args) {

        String content = "This is the content to write into file\n";

        // If the file doesn't exists, create and write to it
        // If the file exists, truncate (remove all content) and write to it
        try (FileWriter writer = new FileWriter("app.log");
             BufferedWriter bw = new BufferedWriter(writer)) {

            bw.write(content);

        } catch (IOException e) {
            System.err.format("IOException: %s%n", e);
        }

    }
}

Sortie

app.log

This is the content to write into file

Pour le mode Ajouter, passez untrue comme deuxième argument dansFileWriter

    // If the file exists, append to it
    try (FileWriter writer = new FileWriter("app.log", true);
         BufferedWriter bw = new BufferedWriter(writer)) {

        bw.write(content);

    } catch (IOException e) {
        System.err.format("IOException: %s%n", e);
    }

2. BufferedWriter (style old school)

Avant le JDK 7try-resources, nous devons gérer lesclose() manuellement. Un souvenir douloureux, voyons ceci:

FileExample2.java

package com.example;

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

public class FileExample2 {

    public static void main(String[] args) {

        BufferedWriter bw = null;
        FileWriter fw = null;

        try {

            String content = "This is the content to write into file\n";

            fw = new FileWriter("app.log");
            bw = new BufferedWriter(fw);
            bw.write(content);

        } catch (IOException e) {
            System.err.format("IOException: %s%n", e);
        } finally {
            try {
                if (bw != null)
                    bw.close();

                if (fw != null)
                    fw.close();
            } catch (IOException ex) {
                System.err.format("IOException: %s%n", ex);
            }
        }
    }
}

Sortie

app.log

This is the content to write into file