File I/O (Input/Output) is a critical concept that allows us to work with data stored in files. File I/O refers to the process of reading from and writing to files. These operations are crucial for interacting with data stored outside of your program, whether it’s text, numbers, or other formats. In Java, File I/O is handled using various classes from the java.io
package.
File I/O Classes in Java
- File: This class represents a file or directory path in the system and provides methods for various file operations like creating, deleting, renaming, and checking file properties (e.g., whether a file exists).
- FileInputStream and FileOutputStream: These classes are used for reading from and writing to binary files (i.e., non-text files like images, audio, etc.).
- FileReader and FileWriter: These classes are used for reading and writing character-based files (i.e., text files).
- BufferedReader and BufferedWriter: These classes wrap around FileReader and FileWriter to provide efficient reading and writing, respectively, by buffering data.
- Scanner: The
Scanner
class can also be used to read files, especially text files, and is often used to parse data from files.
We can also use the java.nio
package for non-blocking, high-performance file operations with classes like Path
, Files
, and FileChannel
.
File Operations in Java
- Creating a File: We can create a new file or check if a file exists using the
File
class. - Reading a File: Java provides classes like
FileReader
andBufferedReader
to read the contents of text files line by line or character by character. - Writing to a File: We can write data to files using
FileWriter
andBufferedWriter
. We can also append data to existing files. - Checking File Properties: The
File
class allows you to check if a file exists, its length, permissions, etc. Methods includeexists()
,length()
, andcanRead()
. - Deleting a File: Files can be deleted using the
delete()
method of theFile
class.