Course Content
Introduction to Java
Java provides a rich set of classes and methods for reading and writing data to and from files. This is known as File Handling and Input/Output (IO) in Java. In this lesson, you will learn the basics of Java File Handling and IO and how to perform common file operations such as reading from a file, writing to a file, and appending to a file.
Creating File Object
The first step in file handling is creating a File
object. You can do this using the File
class in the java.io package. For example, the following code creates a File
object for a file named "example.txt"
in the current directory.
Main.java
Check file exists
Once you have a File
object, you can perform various file operations using the methods provided by the File class. For example, you can check if a file exists using the exists()
method.
Main.java
Read data from a file
To read data from a file, you can use the FileReader
class. This class provides a way to read data from a file character by character. For example, the following code reads the contents of a file named "example.txt"
and prints it to the console:
Main.java
Write data to a file
To write data to a file, you can use the FileWriter
class. This class provides a way to write data to a file character by character. For example, the following code writes the text "Hello, World!"
to a file named "example.txt"
:
Main.java
Append data to a file
If you want to append data to an existing file instead of overwriting it, you can use the FileWriter
class with the true argument, as shown in the following example:
Main.java
In addition to the FileReader
and FileWriter
classes, Java also provides the BufferedReader
and BufferedWriter
classes, which provide a more efficient way to read from and write to files. These classes use a buffer to store data, which helps to reduce the number of disk I/O operations and improve the performance of your file I/O operations.
Conclusion
Java provides a rich set of classes and methods for file handling and IO, making it easy to perform common file operations such as reading from a file, writing to a file, and appending to a file. Using these classes, you can read and write data to and from files simply and efficiently.
How do you create a File object in Java?
Select the correct answer
What is the purpose of the BufferedReader and BufferedWriter classes in Java?
Select the correct answer
Section 5.
Chapter 2