File handling in Java refers to the ability to read from and write to files using the Java programming language. Java provides a comprehensive set of classes and methods that allow you to perform various file operations, such as creating, reading, writing, deleting, and modifying files.
Here’s an overview of the key classes and concepts involved in file handling in Java:
- File: The
File
class represents a file or directory path in the file system. It provides methods to inspect and manipulate files and directories, such as checking if a file exists, creating new files or directories, renaming files, etc. - FileInputStream and FileOutputStream: These classes are used for reading from and writing to binary files, respectively.
FileInputStream
allows you to read data from a file as a stream of bytes, whileFileOutputStream
allows you to write data to a file as a stream of bytes. - BufferedReader and BufferedWriter: These classes are used for reading from and writing to text files, respectively.
BufferedReader
provides methods to read text from a character input stream efficiently, andBufferedWriter
provides methods to write text to a character output stream efficiently. - Scanner: The
Scanner
class is commonly used for reading input from various sources, including files. It provides convenient methods to parse and extract different types of data from a file.
Here’s an example that demonstrates how to read and write data to a file using file handling in Java:
import java.io.*; public class FileExample { public static void main(String[] args) { try { // Writing data to a file FileWriter writer = new FileWriter("output.txt"); writer.write("Hello, World!"); writer.close(); // Reading data from a file FileReader reader = new FileReader("output.txt"); BufferedReader bufferedReader = new BufferedReader(reader); String line = bufferedReader.readLine(); System.out.println(line); bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } }
In this example, the program creates a file called “output.txt” and writes the text “Hello, World!” to it. Then it reads the data from the file and prints it to the console. Finally, it closes the file resources using the close()
method to release system resources.
Remember to handle exceptions appropriately when working with file operations, as file handling operations can throw IOExceptions
.