Java IO Streams represent either an input source, or an output destination where you are trying to send receive/data. This can be to a console window, reading a file from a disk (or SSD), network communication, etc.
Java uses the concept of IO streams, and how to handle them, almost identically between all sources. This makes using any of them easy once you learn how to use the first one.
A Stream is a sequence of data, where one item is sent at a time. Some streams just pass the data as is, other times the data must be transformed to be useful.
Opening and Closing Streams
An important thing to remember about streams, is that you have to open them to/from the respective source. That also means you need to remember to close the stream.
Note: If you open it, you must close it.
Byte vs Character Streams
There are two major types of Streams, Byte and Character. Now all streams extend the Byte Streams, so one might think you should use those. However, they are low-level manipulators, and in Java you want to use higher level Classes when possible.
This means, you should use character streams whenever possible.
Pseudocode of Streams in Java
While each type of stream is different, we want to look at the basics of opening and using a Stream in Java. So consider the basic situation below.
void sampleStreamUse(String source) {
InputStream in = null;
try {
in = new InputStream(source);
while(in.notEmpty()) {
System.out.println(in.readLine());
}
} catch(IOStreamException ioex) {
// do error stuff
} finally {
// do finally error stuff
in.close();
}
}
While none of this code is real, you can get a feel for how the IO would work. You will need to wrap all of your IO in a try/catch because of how many potential errors you might run into that you cannot control, such as a source being unavailable, corrupted, etc.
Your finally is where you often close out your streams in case you cannot close them due to an error that was thrown.
Java IO Streams was originally found on Access 2 Learn
One Comment
Comments are closed.