Lesson 8 | Writing streams |
Objective | Create writer streams that write data. |
Writing Java Streams
The write()
method is the primary method used to write to streams. Similar to the read()
method, the write()
method comes in a variety of different forms. Following is an example of writing characters to a character array stream:
CharArrayWriter out = new CharArrayWriter(16);
out.write('A');
out.write('B');
out.write('C');
System.out.println(out);
Character Array
In this example, a character array writer is created with its initial buffer size set to 16 characters. The characters A, B, and C are written to
the stream, after which the contents of the stream buffer are printed to standard output. The System.out
standard output object is a PrintStream
object, which is similar to a PrintWriter
object.
This means that the familiar println()
method is actually defined in the PrintStream
class.
What is the difference between writing Streams in Java 1.1 and writing Streams in Java SE 8?
The process of writing streams in Java has evolved over time, with significant changes being introduced in Java SE 8. Some of the key differences between writing streams in Java 1.1 and writing streams in Java SE 8 include:
- Improved Stream API: In Java SE 8, the java.util.Stream API was introduced, which provides a more powerful and flexible way to process collections of data, including streams of data. The Stream API provides a variety of operations for processing streams, including filter, map, reduce, and collect, and also provides support for parallel processing.
- Lambda Expressions: Java SE 8 introduced support for lambda expressions, which provide a way to pass code as a value and can be used to write more concise and expressive code when working with streams. This makes it easier to write code that manipulates streams, and also makes the code more readable and maintainable.
- Method References: Java SE 8 introduced support for method references, which provide a shorthand way to refer to a method without having to write a lambda expression. This makes it easier to write code that manipulates streams, and also makes the code more readable and maintainable.
- Stream Operations: Java SE 8 introduced a variety of new stream operations, including operations for filtering, mapping, reducing, and collecting, as well as operations for performing actions on the elements of a stream, such as forEach and peek.
- Parallel Processing: Java SE 8 introduced support for parallel processing of streams, which provides a way to process streams in parallel, taking advantage of multi-core processors and providing a more scalable solution for processing large amounts of data.
Overall, the improvements in the Stream API, along with the addition of lambda expressions and method references, have made writing streams in Java SE 8 a more powerful, flexible, and expressive experience, compared to writing streams in Java 1.1.