File Handling In Java

File handling is a critical aspect of any programming language.

File handling refers to manipulating files and directories on the file system. This article will provide an overview of file handling in Java. Class

The File class in Java is the primary way to handle files and directories. It is part of the package, which is used for input and output operations.

The File class has two constructors:

  • One that takes a String representing the file path
  • Another File object representing the file path

Creating File In Java

The code below demonstrates how to create a new file.

The above code creates a new file named “file.txt”.

If the file does not exist, the createNewFile() method will create the file and return true.

If the file already exists, the method will return false.

If there is an exception during file creation, an IOException will be thrown.

Reading File In Java

To read a file in Java, you can use the FileReader class. The FileReader class is a subclass of the InputStreamReader class, which reads bytes and decodes them into characters.

The code below demonstrates how to read a file.

The above code reads the contents of the “file.txt” file and prints them to the console.

The read() method returns the next character in the file as an integer. If the end of the file has been reached, the method returns -1.

Writing a File In Java

To write to a file in Java, you can use the FileWriter class. The FileWriter class is a subclass of the OutputStreamWriter class, which writes characters to a byte stream.

The code below shows how to write to a file.,

The above code writes the string “Hello, World!” to the “file.txt” file.

The write() method writes a string to the file. If the file already contains data, the write() method will overwrite it.

How to Close a Opened File In Java

Closing a file releases system resources associated with the file. You can close a file using the close() method.

The code below shows how to close to a file.,


File handling is an essential part of programming, and Java provides several classes to handle files and directories. We explored the basics of file handling in Java using the File class, FileReader class, and FileWriter class.

Still there are FileInputStream, FileOutputStream and nio classes in Java which efficiently reads/writes files and do file operations in Java.

We covered how to create a file, read a file, write to a file, and close a file. By using these techniques, you can handle files and directories in your Java programs.