File Input Output in Java

Published on 13 October 2019 (Updated: 10 October 2022)

Welcome to the File Input Output in Java page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileInputOutput {

    public static void main(String[] args) {
        File file = new File("output.txt");
        writeToFile(file);
        readFile(file);
    }

    public static void readFile(File file) {

        try {

            BufferedReader buffer = new BufferedReader(new FileReader(file));
            try {
                String nextLine = buffer.readLine();
                while (nextLine != null) {
                    System.out.println(nextLine);
                    nextLine = buffer.readLine();
                }
                buffer.close();
            } catch (IOException e) {

                System.out.println("Error occurred while reading the file");
            }

        } catch (FileNotFoundException e) {

            System.out.println("Error occurred while opening the file!");
        }

    }

    public static void writeToFile(File file) {

        String content = "We wish you a Merry Christmas\n" +
                "We wish you a Merry Christmas\n" +
                "We wish you a Merry Christmas\n" +
                "And a happy New Year.";
        try {
            FileWriter writer = new FileWriter(file);
            writer.write(content);
            writer.close();
        } catch (IOException e) {

            System.out.println("Error occurred while writing contents to file!");
        }

    }

}

File Input Output in Java was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.