I/O (Input/Output) streams are used to read data from input sources (like files, network connections) and write data to output destinations (like files, network connections). They provide a standard way to handle different types of data sources and destinations, allowing Java programs to interact with the outside world.
I/O streams make it possible for Java programs to interact seamlessly with the external world, handling various types of data efficiently and consistently.
InputStream
and OutputStream
are used for byte streams.Reader
and Writer
are used for character streams.InputStream
include FileInputStream
(for reading from files) and BufferedInputStream
(for efficient reading using a buffer).OutputStream
include FileOutputStream
(for writing to files) and BufferedOutputStream
(for efficient writing using a buffer).import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStreamExample {
public static void main(String[] args) {
// Writing bytes to a file
try (FileOutputStream fos = new FileOutputStream("example.txt")) {
String data = "Hello, Byte Streams!";
fos.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
// Reading bytes from a file
try (FileInputStream fis = new FileInputStream("example.txt")) {
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Reader
and Writer
, which are abstract classes that define methods for reading and writing characters.Reader
include FileReader
(for reading from files) and BufferedReader
(for efficient reading using a buffer).