java organizes I/O into byte and character streams, each with specific class for different tasks.
byte stream
- handle raw binary data
- base classes
InputStream- Abstract class for reading bytesOutputStream- Abstract class for writing bytes
- common subclasses -
FileInputStream,FileOutputStream- read/write bytes from/to files.BufferedInputStream,BufferedOutputStream- use buffering to reduce direct access to the underlying system.DataInputStream,DataOutputStream- read/write primitive data typesObjectInputStream,ObjectOutputStream- serialize/deserialize objects.
import java.io.*;
public class ByteStreamExample {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt")) {
int byteData;
while ((byteData = fis.read()) != -1) { // Read byte-by-byte
fos.write(byteData); // Write byte
}
} catch (IOException e) {
System.out.println("IO Error: " + e.getMessage());
}
}
}
character streams
- handles unicode characters, ideal for text data.
- base classes -
Reader- abstract class for reading charactersWriter- abstract class for writing characters.
- common subclasses -
FileReader,FileWriter- read/write characters to/from files.BufferedReader,BufferedWriter- buffer characters data for efficiency.InputStreamReader,OutputStreamWriter- bridge bytes streams to character streams
import java.io.*;
public class CharStreamExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
System.out.println("IO Error: " + e.getMessage());
}
}
}
predefined streams
system.insystem.outsystem.err