File Handling in Java With Examples

File Handing in java comes under IO operations. Java IO package java.io classes are specially provided for file handling in java.

File Handling in Java

Some of the common file handling operations are;

  1. Create file
  2. Delete file
  3. Read file
  4. Write file
  5. Change file permissions

Let’s look into each of these file handling operations through java program example.

Create File

We can use File class createNewFile() method to create new file. This method returns true if file is successfully created, otherwise it returns false. Below is a simple program showing how to create a new file in java.

Above image shows the output produced in first run, in subsequent execution the file will be present so the createNewFile will return false.

There are some rules associated with absolute path and relative path, read about them at java create new file.

Delete File

File class delete method is used to delete a file or an empty directory. Below is a simple example to delete a file.

File delete method returns true if file is deleted successfully or else it returns false.

file-handling-in-java-delete

Further Reading: Java delete file

Read File

There are many ways to read a file in java. We can use BufferedReader, FileReader or Files class. Below code snippet is to read file line by line.

For all other ways to read file, go to java read file.

Write File

We can use FileWriter, BufferedWriter, Files or FileOutputStream to write file in java. Below code snippet use Stream to write data to file.

For a complete example with other classes, refer java write to file.

Change File Permissions

File class provide methods to get file permission details as well as change them. Below code snippet shows you how to read file permissions and change them.

However if you are using Java 7 or higher version, you should use PosixFilePermission that provides more options.

Read more about PosixFilePermission

That’s all about file handling in java. I hope it will help you in getting started with file operations in java programs.

By admin

Leave a Reply