Govt. Exams
Entrance Exams
FileOutputStream is NOT thread-safe. When multiple threads write simultaneously, race conditions can cause data corruption or interleaved writes. Solutions include: synchronizing access using synchronized blocks, using thread-safe wrapper classes, or employing a single-threaded writer pattern with a queue. PrintWriter with autoFlush provides some buffering protection.
PushbackInputStream allows you to 'unread' bytes using the unread() method. This is useful for parsers that need to look ahead without consuming the data.
BufferedInputStream provides automatic buffering (8KB default), and DataInputStream allows reading typed data. Together they enable efficient reading of large binary files without loading everything into memory.
During deserialization, the constructor is NOT called. readObject() restores the object state directly from the serialized data. This is why transient fields need special handling.
RandomAccessFile allows you to read/write at any position in a file using seek() method. Sequential streams can only read/write sequentially from current position.
RandomAccessFile supports seek() operation to jump to specific file positions, useful for reading log tail or accessing specific records directly.
ObjectInputStream/ObjectOutputStream with serialVersionUID ensures compatibility, versioning, and is the standard approach for object persistence in Java.
PrintWriter uses buffering by default. If flush() or close() is not called, buffered data may not be written to disk.
FileChannel.transferTo() uses OS-level optimizations for file copying, and NIO channels with direct buffers are most efficient for large file transfers.
Maintaining a constant serialVersionUID and implementing version-aware readObject() methods allows deserializing objects from different class versions.