File handling
Introduction to File Handling
File handling is a crucial aspect of programming as it allows data to be saved and accessed in files. It enables a program to store data permanently, which can then be used by the program in future executions.
Reading and Writing Files:
In Java, we can use the File
class to represent a file and the FileWriter
and FileReader
classes to read and write files. The following code snippet demonstrates how to write data to a file using FileWriter
:
Working with Text Files and Binary Files:
Java provides different classes to handle text files and binary files. The FileWriter
and FileReader
classes are used to read and write text files, while the ObjectOutputStream
and ObjectInputStream
classes are used to read and write binary files. The following code snippet demonstrates how to write an object to a binary file using ObjectOutputStream
:
Error Handling:
When working with files, it is important to handle errors that may occur. This can be achieved using try-catch blocks. The following code snippet demonstrates how to read data from a file using FileReader
and handle any errors that may occur:
In the above code snippet, we are reading data from a file using FileReader
and displaying it to the console. The read()
method of FileReader
returns -1 if the end of the file is reached.
Overall, file handling is an important aspect of programming and is useful in a variety of applications, from storing user preferences to saving game progress.
Last updated