FileInputStream and FileOutputStream are two fundamental classes in Java used for reading from and writing to files, respectively. They are part of the Java I/O (Input/Output) package and operate on byte streams, making them suitable for handling binary data.
FileInputStream
- Purpose: FileInputStream is used to read raw byte data from a file.
- Usage: It is commonly used for reading binary files (such as images, audio files, etc.) or text files in binary mode.
- Constructor: You can create a FileInputStream by passing the name of the file or a File object.
- Methods:
- read(): Reads the next byte of data from the input stream. Returns an integer value (0-255) or -1 if the end of the stream is reached.
- read(byte[] b): Reads some bytes from the input stream into an array of bytes.
- close(): Closes the input stream and releases any system resources associated with it.
Example of FileInputStream
import java.io.FileInputStream; public class FileInputStreamExample { |
FileOutputStream
- Purpose: FileOutputStream is used to write raw byte data to a file.
- Usage: It is typically used for writing binary files or appending data to existing files.
- Constructor: You can create a FileOutputStream by passing the name of the file or a File object. You can also specify whether to append to the file using a second parameter.
- Methods:
- write(int b): Writes the specified byte to the output stream.
- write(byte[] b): Writes an array of bytes to the output stream.
- close(): Closes the output stream and releases any system resources associated with it.
Example of FileOutputStream
import java.io.FileOutputStream; public class FileOutputStreamExample { |
Summary
- FileInputStream: Used for reading byte data from files. Suitable for binary file reading.
- FileOutputStream: Used for writing byte data to files. Suitable for binary file writing.
Both classes are essential for low-level file operations in Java, enabling the handling of binary data effectively.