You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This section will show how streams are used for input/output (IO) processing
IO refers to how data is read from a resource, or writter to a resource.
The streams here are unrelated to the streams in chapter 4!
🟥 8.2.1 Stream Fundamentals
Contents of a file may be accessedor written via a stream, which is a list of data elements presented sequentially
🟥 8.2.2 Stream Nomenclature
The java.io API has multiple classes for accessing, creating and manipulating streams.
🟡 Byte Streams vs Character Streams
The java.io API has two sets of classes denoted by their name for reading and writing streams:
Those which contain Stream in their name
Thos which contain Reader/Writer in their name
E.g. we have a FileInputStream and FilleReader classes
Stream classes are used for inputting and outputting all types of binary or byte data
Reader and Writer classes are used for inputting and outputting only Character and String data
🟡 Input and Output
Most classes have either an Input or Output corresponding class.
E.g. we have FileOutputStream for writing data which can be read by FileInputStream
Also most classes have a corresponding Reader or Writer class
E.g. we have a FilerWriter for writing data which can be read by FileReader class
There are exceptions, e.g. PrintWriter does NOT have a corresponding PrintReader class
🟡 Low-Level vs High-Level Streams
A low level stream connects directly with the source of the data like a file, array or String - they process the raw data or resource and are accessed in an unfiltered way. E.g. FileInputStream is a class which reads a file one byte at a time.
A high level stream is built on top of another stream using wrapping - an instance is passed to a constructor of another class
E.g. here is FileReader used as a low-level stream, and BufferedReader is the high-level stream:
If the limit is exceeded, an exception MAY be thrown. As you can see here, the program was fine!
🟡 Skipping Over Data
The IntputStream and Reader classes also have a skip(long) method which allow you to skip over a number of bytes. It returns the actual number of byters which were skipped.
If it returns a value less than 1, then no bytes were skipped
Assume we have an instance of InputStream instance whose next values are TIGERS:
InputStreamis = ...;
System.out.println((char)is.read()); // prints Tis.skip(2); // skips IGis.read(); // E is NOT printedSystem.out.println((char)is.read()); // prints RSystem.out.println((char)is.read()); // prints S