i

JAVA Complete Course

File Handling

File handling in Java implies reading from and writing data to a file. The File class from the java.io package, allows us to work with different formats of files. In order to use the File class, you need to create an object of the class and specify the filename or directory name.

We have already mentioned that operations are made on InuptStream and OutputStream subclasses. We also can create a file from our Java application with the help of methods of File class. Speaking abstract only about files can be hard, and let’s see one big example which will contain three steps:

1. Creating File

2. Writing data in that file

3. Reading data from created file

For this example we can use clean code principles and make three different classes for each operation and then in main class (Main method) call them in the meaningful order. Let’s create classes FileCreator, DataWriter and DataReader.

A screenshot of a cell phone

Description automatically generated

A screenshot of a cell phone

Description automatically generated

A screenshot of a cell phone

Description automatically generated

 

We have already created all classes, now just create one class where we will run operations in meaningful order:

A screenshot of a cell phone

Description automatically generated