DEV Community

Mohamed Ajmal
Mohamed Ajmal

Posted on

Java File Handling.

In Java, file handling means working with files like creating them, reading data, writing data or deleting them. It helps a program save and use information permanently on the computer.

Why File Handling is Required?

To store data permanently instead of keeping it only in memory.
To read and write data from/to files for later use.
To share data between different programs or systems.
To organize and manage large data efficiently.
Enter fullscreen mode Exit fullscreen mode

To support file handling, Java provides the File class in the java.io package.

Operations

  1. *Create a File *- In order to create a file in Java, you can use the createNewFile() method. If the file is successfully created, it will return a Boolean value true and false if the file already exists.

  2. Write to a File - We use the FileWriter class along with its write() method in order to write some text to the file.

  3. Read from a File - In Java, the read() method is used with classes like FileReader or InputStream to read data from a file one character or byte at a time.

    It returns an integer value representing the character or byte read.When the end of the file is reached, the method returns -1 indicating no more data is available.

  4. canRead a File - canRead() check if the file is readable.

5.canWrite a File - canWrite() checks whether the file can be written to by the program.

  1. Existance of a File - exists() checks whether the specified file or directory exists on the file system.

  2. Getting a path - getAbsolutePath() returns the full path of the file or directory in the file system.

  3. Delete a File - We use the delete() method in order to delete a file.

Top comments (0)