File Input Output in Java

Published on 28 April 2022 (Updated: 18 September 2022)

File Input Output in Java

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.

Note: The solution shown above is the current solution in the Sample Programs repository as of May 16 2022 11:56:20. The solution was first committed on Oct 13 2019 18:50:32. As a result, documentation below may be outdated.

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.