W3docs

Java FileOutputStream Create File if not exists

To create a file using FileOutputStream in Java if it does not exist, you can use the following code:

To create a file using FileOutputStream in Java if it does not exist, you can use the following code:


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

public class Main {
    public static void main(String[] args) {
        try (FileOutputStream fos = new FileOutputStream("output.txt")) {
            // File is created automatically if it does not exist
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The FileOutputStream constructor automatically creates the file if it does not exist. The example above uses a try-with-resources block to ensure the stream is properly closed after use.

Alternatively, you can use the FileOutputStream(String name, boolean append) constructor, which creates a new file if it does not exist and allows you to specify whether to append to the file or overwrite it:


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

public class Main {
    public static void main(String[] args) {
        try (FileOutputStream fos = new FileOutputStream("output.txt", false)) {
            // false overwrites the file; true appends to it
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I hope this helps. Let me know if you have any questions.