Junior
What are the basic implementations of input/output streams in Java?
sobes.tech AI
Answer from AI
In Java, the basic implementations of input-output streams are represented by class hierarchies:
-
Byte Streams: Work with data byte-by-byte (8 bits). Basic classes:
InputStreamandOutputStream.FileInputStream,FileOutputStream- for working with files.ByteArrayInputStream,ByteArrayOutputStream- for working with byte arrays in memory.PipedInputStream,PipedOutputStream- for creating communication channels between streams.SequenceInputStream- combines multipleInputStreamsequentially.FilterInputStream,FilterOutputStream- base classes for decorators that add functionality (e.g., buffering, reading primitive types).
-
Character Streams: Work with characters (Unicode encoding), using byte streams or directly. Basic classes:
ReaderandWriter.FileReader,FileWriter- for working with files, automatically handle encoding.CharArrayReader,CharArrayWriter- for working with character arrays in memory.StringReader,StringWriter- for working with strings.PipedReader,PipedWriter- character analogs ofPipedInputStreamandPipedOutputStream.InputStreamReader,OutputStreamWriter- bridges between byte and character streams, allowing to specify encoding.FilterReader,FilterWriter- base classes for decorators.
-
Buffered Streams: Wrappers over other streams to improve performance through buffering.
BufferedInputStream,BufferedOutputStreamBufferedReader,BufferedWriter
-
Data Streams: Wrappers for reading/writing primitive data types (int, double, etc.) and strings in a machine-independent format.
DataInputStream,DataOutputStream
-
Object Streams: For serialization/deserialization of objects.
ObjectInputStream,ObjectOutputStream
Example of using FileInputStream:
import java.io.FileInputStream;
import java.io.IOException;
public class FileReadExample {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("example.txt")) {
int data;
while ((data = fis.read()) != -1) { // Read byte-by-byte
System.out.print((char) data); // Convert byte to character
}
} catch (IOException e) {
e.printStackTrace();
}
}
}