File is a computer resource / object for storing variety of data including text, image, video, etc.
We can easily store data in variables, then why do we need a file? Files are required to persist data i.e. sustain data even when computer is shutdown. The data stored in variables stay in memory only during the program execution, thereafter it is cleared i.e. it is temporary. To permanently store data, we need Files.
A computer has two types of memory :
- Primary / RAM (Random Access Memory)
- Used to store temporary data
- Stores data only while the program is being executed
- Cleared when computer is shutdown
- Secondary / ROM (Read Only Memory)
- Used to store data permanently i.e. even when computer is shutdown.
The programs that we write are saved in .kt
files on the secondary memory. When we run the program, program and its required data is brought into primary memory for execution. All variables declared and used in the program are also saved in primary memory. Once the program execution is complete, all its data in Primary memory is cleared. If we want to save the data such that it survives not only program completion but computer shutdown also, then we have save in files on the secondary memory.
Example - suppose we are writing a Word document and it is not yet saved in a file. If we try closing the window, applicat warns us that progress will be lost if not saved. This is because while we write the document, it is saved in primary memory. If we do not save but close the application, then data will be lost. Only when we save it in a file on secondary memory, we will be able to reopen it after closing the application or even after computer restarts.