Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you wrap FileOutputStream with a DataOutputStream? [closed]

Tags:

java

A DataOutputStream can wrap a FileOutputStream, but I don't understand why it has been used here.

FileOutputStream fos = new FileOutputStream(args[0]);
DataOutputStream dos = new DataOutputStream(fos);
dos.writeByte('j');

The last line does the same as fos.write('j'); What does DataOutputStream add in this situation? i.e. why is there?

like image 497
prjndhi Avatar asked Sep 05 '25 15:09

prjndhi


1 Answers

Streams in Java are defined according to the Decorator design pattern.

This means that you can compose a specific functionality (implemented inside a specific stream class) with another stream. This allows you to customize what you can do with streams. In your specific example

  • a FileOutputStream is a concrete component which provides the functionality to write to a stream that is mapped to a File
  • a DataOutputStream is a concrete decorator that, attached to another decorator or component, is able to extend the functionality by giving you a way to write primitives onto the stream, without caring about what there is in the underlying chain of decoration
like image 103
Jack Avatar answered Sep 08 '25 04:09

Jack