FileOutputStream in Java

It extends OutputStream. A file output stream is an output stream for writing data to a File or to a FileDescriptor.

Methods in FileOutputStream

FileOutputStream in Java

package com.java.io;


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

public class FileOutputStreamExample {

    public static void main(String[] args) {

        FileOutputStream fos = null;
        File file;
        String data = "Test data";

        try {
            file = new File("/Test/TestFolder/test-file1.txt");
            fos = new FileOutputStream(file);

            /*
             * Create new file if it does not exists
             */
            if (!file.exists()) {
                file.createNewFile();
            }
            byte[] bytesArray = data.getBytes();
            fos.write(bytesArray);
            fos.flush();
            System.out.println("Data written to File");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException ioe) {

            }
        }
    }

}
Data written to File

File

Screen Shot 2020-03-24 at 6.24.35 PM

Related Article

Byte Stream Hierarchy in Java

Leave a Reply

Your email address will not be published. Required fields are marked *