DEV Community

Divya Divya
Divya Divya

Posted on

File Handling in Java

File Handling:

  • File Handling is used to create, read , write , update , and delete files.
  • It using the program data stored permanently in the hard disk.So, that program after executed data does not deleted.
  • Java provides classes such as File , FileWriter , FileReader , BufferWriter and BufferedReader for file handling.

Example:
In a student management system , student details can be saved in a file and read again later when needed.

Why File Handling needed in Java

File handling is necessary for:

  • Data Persistence: Data saved in a file can be used later, even after the program is closed.
  • Data Communication: Files help different programs share data with each other.
  • Large Data Storage: Files can store large amounts of data that cannot fit in memory.
  • Log Management: Files can store logs to track program activities and help find errors.

Common File Handling Methods:
File handling methods in Java are createNewFile(), exists(), delete(), getName(), getAbsolutePath(), getCanonicalPath(), write(), read(), and close(). These methods are used to create, access, read, write, and manage files.

getAbsolutePath VS getCanonicalPath

AbsolutePath and CanonicalPath are used to get the locaation of a file in Java.

AbsolutePath:Return the complete path of the file exactly as it is specified. It does not remove special symbol like . and .. .

CanonicalPath:Returns the actual and unique path of the file by resolving and removing . and ...

Example

folder/../sample.txt

AbsolutePath
folder\..\sample.txt
Full path as written.

CanonicalPath
sample.txt
Cleaned and actual path.

Top comments (0)