So schreiben Sie eine Datei in Java - FileOutputStream

So schreiben Sie in eine Datei in Java - FileOutputStream

In Java istFileOutputStream eine Byte-Stream-Klasse, die zum Verarbeiten von binären Rohdaten verwendet wird. Um die Daten in eine Datei zu schreiben, müssen Sie die Daten in Bytes konvertieren und in einer Datei speichern. Siehe unten vollständiges Beispiel.

package com.example.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFileExample {
    public static void main(String[] args) {

        FileOutputStream fop = null;
        File file;
        String content = "This is the text content";

        try {

            file = new File("c:/newfile.txt");
            fop = new FileOutputStream(file);

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            // get the content in bytes
            byte[] contentInBytes = content.getBytes();

            fop.write(contentInBytes);
            fop.flush();
            fop.close();

            System.out.println("Done");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fop != null) {
                    fop.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Ein aktualisiertes JDK7-Beispiel mit der neuen Methode "Try Resource Close", um Dateien einfach zu verarbeiten.

package com.example.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFileExample {
    public static void main(String[] args) {

        File file = new File("c:/newfile.txt");
        String content = "This is the text content";

        try (FileOutputStream fop = new FileOutputStream(file)) {

            // if file doesn't exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            // get the content in bytes
            byte[] contentInBytes = content.getBytes();

            fop.write(contentInBytes);
            fop.flush();
            fop.close();

            System.out.println("Done");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Verweise

  1. http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileOutputStream.html

  2. //java/how-to-read-file-in-java-fileinputstream/