Monday, April 28, 2025

Java OO Tutorial - Write and Append to File in Java

In this Java code, we are writing a string to a file named "externalfile.txt". The program tries to open the file using FileWriter and then writes the string to the file using the write() method. Finally, it closes the file using the close() method.

The try-catch block is used to handle any exceptions that may be thrown while writing to the file. If an exception occurs, an error message is displayed on the console.

The finally block is used to execute code that needs to be run regardless of whether an exception occurred or not. In this case, the "I am all over the place" message is displayed on the console.

This program demonstrates how to write data to a file in Java using FileWriter class.

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Main {	
	
	public static void main(String[] args) {
		
		try {
			FileWriter fileObj = new FileWriter("externalfile.txt");
			fileObj.write("I will end up in external file\n");
			fileObj.close();
			System.out.println("Operation done.");
		} catch (IOException fError) {
			System.out.println(fError);
		} finally {
			System.out.println("I am all over the place.");
		}				
	}		
}

Here's a breakdown of the code block by block: 

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

This block of code imports necessary classes for file operations, including File, FileWriter, and IOException

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

This block of code begins the definition of the Main class and the main() method. 

try {
	FileWriter fileObj = new FileWriter("externalfile.txt");
	fileObj.write("I will end up in external file\n");
	fileObj.close();
	System.out.println("Operation done.");
}

This block of code uses a try block to write a string to a file named "externalfile.txt".

A FileWriter object named fileObj is created, which represents the file we want to write to.

The write() method is then called on fileObj to write the string "I will end up in external file" to the file, followed by a new line character.

Finally, the close() method is called on fileObj to close the file. 

catch (IOException fError) {
	System.out.println(fError);
}

This block of code uses a catch block to catch any IOException that may occur while writing to the file. If an exception is caught, an error message is printed to the console. 

finally {
	System.out.println("I am all over the place.");
}				

This block of code uses a finally block to execute code that needs to be run regardless of whether an exception occurred or not. In this case, the message "I am all over the place" is printed to the console.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...