In this lesson, we will learn how to read from and write to files in Java. File I/O (Input/Output) is a way to handle files in your programs. This is useful when you want to save data or read data from a file.
To read a file in Java, we can use the FileReader and BufferedReader classes. Here is a simple example:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("example.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}In this example, we create a FileReader object to read from a file called "example.txt". We then create a BufferedReader object to read the file line by line. The readLine() method returns the next line from the file, or null if there are no more lines. We print each line to the console using System.out.println(). Finally, we close the BufferedReader to free up system resources.
To write to a file in Java, we can use the FileWriter and BufferedWriter classes. Here is a simple example:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
try {
FileWriter fileWriter = new FileWriter("example.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("Hello, World!");
bufferedWriter.newLine();
bufferedWriter.write("This is a test file.");
bufferedWriter.close();
} catch (IOException e) {
System.out.println("Error writing file: " + e.getMessage());
}
}
}In this example, we create a FileWriter object to write to a file called "example.txt". We then create a BufferedWriter object to write to the file. The write() method writes a string to the file, and the newLine() method writes a newline character to the file. Finally, we close the BufferedWriter to free up system resources.
Remember to handle exceptions when working with files, as they can throw IOExceptions if there is an error reading or writing the file.
<< Previous | Home | Next >>