Logo
Unit 9 – Basic File I/O in Java

Basic File I/O in Java

Duration: 5 minutes

Hello, Java learners!

Today, we’ll explore Basic File Input/Output (I/O) in Java. File I/O is an integral part of programming, allowing you to read from and write to files. This is crucial for many applications, such as data processing, logging, or configuration handling.In Java, the java.io package contains classes for system input and output through data streams, serialization, and the file system.

1. Writing to a File

To write to a file in Java, you can use the FileWriter class along with BufferedWriter.

Example:

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileExample {
 public static void main(String[] args) {
 try {
 FileWriter writer = new FileWriter("example.txt");
 BufferedWriter buffer = new BufferedWriter(writer);
 buffer.write("Hello, World!");
 buffer.close();
 System.out.println("Successfully wrote to the file.");
 } catch (IOException e) {
 System.out.println("An error occurred.");
 e.printStackTrace();
 }
 }
}

2. Reading from a File

To read from a file, you can use the FileReader class along with BufferedReader.Example:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
 public static void main(String[] args) {
 try {
 FileReader reader = new FileReader("example.txt");
 BufferedReader buffer = new BufferedReader(reader);
 String line;
 while ((line = buffer.readLine()) != null) {
 System.out.println(line);
 }
 buffer.close();
 } catch (IOException e) {
 System.out.println("An error occurred.");
 e.printStackTrace();
 }
 }
}

Exercise: Create a Simple File I/O Operation

Your exercise is to create a Java program that performs the following:- Write a short message or a list of items to a file.

  • Read the contents of the file and print them to the console.

Conclusion

Well done! You’ve just learned the basics of file I/O in Java. File handling is a powerful skill that opens up numerous possibilities for data manipulation and storage in your programs.Practice these concepts by creating different files and experimenting with reading and writing various types of data.Keep exploring, and enjoy your Java programming journey!

Next Tutorial: Exception Handling in Java

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!