File Handling
File handling refers to the ability of a Java program to create, read, write, and delete files stored on a computer's disk. Java provides the File class and related classes to work with files and folders.
1. What is File Handling?
File handling refers to the ability of a Java program to create, read, write, and delete files stored on a computer's disk. Java provides the File class and related classes to work with files and folders.
2. Why is it used?
Programs often need to save data permanently (so it's still available after the program closes) or read data that already exists on disk, like a configuration file or a saved report. File handling makes this possible.
3. Real-Life Example
Think of writing important notes in a physical notebook so you can refer back to them later, even after closing the notebook and putting it away. File handling lets a program "write in its notebook" and "read it back" whenever needed.
4. Syntax
javaFile file = new File("filename.txt"); boolean exists = file.exists();
5. Example Program
javaimport java.io.File; public class FileHandlingDemo { public static void main(String[] args) { File file = new File("sample.txt"); System.out.println("File exists: " + file.exists()); } }
Output:
File exists: false(Output depends on whether "sample.txt" actually exists in the program's folder.)
6. Key Points to Remember
- The
Fileclass represents a file or folder path, but doesn't read or write content by itself — other classes handle that. - Common file operations include checking existence, creating, deleting, and renaming.
- File paths can be relative (based on the current folder) or absolute (the complete path from the root).