OOP Lab 12
OOP Lab 12
Fall 2024
Lab 12
Objective:
Student Information
Student Name
Student ID
Date
Assessment
Marks Obtained
Remarks
Signature
LAB 12
File Handling in Java
Objectives
Discuss the importance of file handling in programming.
Explain the basic file operations: read, write, and delete.
Apparatus:
Hardware requirements:
Dual core CPU based on x64 architecture
Minimum of 1 GB RAM
800 MB of disk space
Software requirements:
Windows 7 SP1 (64 bit)
Java JDK 8 (64 bit JVM)
NetBeans IDE (version 8.1 or above)
Background:
The file handling plays an important role when the data needs to be stored permanently into the file. A
file is a named location on disk to store related information. We can access the stored information
(nonvolatile) after the program termination. File handling is an important part of any application.
Java has several methods for creating, reading, updating, and deleting files.
.
The File class has many useful methods for creating and getting information about files. For example:
.
To create a file in a specific directory (requires permission), specify the path of the file and use double
backslashes to escape the "\" character (for Windows). On Mac and Linux you can just write the path,
like: /Users/name/filename.txt
Write To a File
In the following example, we use the FileWriter class together with its write() method to write some
text to the file we created in the example above. Note that when you are done writing to the file, you
should close it with the close() method:
Read a File
In the previous chapter, you learned how to create and write to a file. In the following example, we
use the Scanner class to read the contents of the text file we created in the previous chapter:
.
Get File Information
To get more information about a file, use any of the File methods:
.
Delete a File
To delete a file in Java, use the delete() method:
.
Exercises:
1. Write a Java program that reads a text file and prints its content to the console. Enhance
the program to display the number of lines in the file.
2. Create a Java program that writes a series of strings to a new text file. Modify the program
to append new strings to the existing file instead of creating a new one.