Java File Handling

What is File Handling?

File handling allows a program to save data to a file and read data from a file. This is important for storing information permanently.

Java provides built-in classes like File, Scanner, and FileWriter to work with files.

Loading...
Output:

Creating a File

You can create a new file using the createNewFile() method. This method throws an exception if something goes wrong.

Loading...
Output:

Writing to a File

Use FileWriter to write text to a file. This will overwrite the file unless you enable append mode.

Loading...
Output:

Reading from a File

Use the Scanner class to read file content line by line.

Loading...
Output:

Appending to a File

To add content without deleting existing data, enable append mode by passing true to FileWriter.

Loading...
Output:

Deleting a File

You can delete a file using the delete() method from the File class.

Loading...
Output:

Handling Exceptions

File operations can fail due to missing files or permission issues. Use try-catch to handle these safely.

Loading...
Output:

Practice

Create a program that writes student names to a file, reads them back, and prints them.

Loading...
Output:

Need Help?