Introduction to Java I/O
The java.io package contains nearly all the classes you might need in Java to perform input and output (I/O) operations. These classes enable your Java programs to read data from a source (such as a file, memory, or network socket) and write data to a destination.
The File Class
The java.io.File class is an abstract representation of file and directory pathnames. It does not allow you to read or write the actual contents of a file. Instead, it is used to interact with the file system—navigating directories, checking permissions, creating/deleting files, and querying metadata.
Byte Streams
Byte Streams are the foundation of Java I/O. They are used to read and write raw, binary data (8-bit bytes), making them ideal for handling files like images, audio files, video files, database files, and network packets.
Character Streams
While byte streams handle raw binary files, Character Streams are specifically designed to read and write text files. They automatically handle Unicode character translation between character sets (such as UTF-8 or UTF-16) and the platform's default encoding scheme.
Buffered Streams
By default, standard streams like FileInputStream and FileWriter execute I/O operations directly through the operating system. This means every read or write request is handled directly by the disk or network, which is extremely inefficient and slow.
Data and Object Streams
Beyond simple bytes and text, Java programs frequently need to read and write more complex structures. Java provides Data Streams for working with primitive data types, and Object Streams for converting entire Java objects into streams of bytes—a process called Serialization.
PrintStream and PrintWriter
Java provides PrintStream and PrintWriter to write formatted data to a destination. The most famous example of a print stream is System.out, which is an instance of PrintStream.