![]() ![]() ![]() |
Start of Tutorial > Start of Trail > Start of Lesson | Search |
TheSequenceInputStream
creates a single input stream from multiple input sources. This example program,
Concatenate
, uses
SequenceInputStream
to implement a concatenation utility that sequentially concatenates files together in the order they are listed on the command line.This is the controlling class of the
Concatenate
utility:The first thing that theimport java.io.*; public class Concatenate { public static void main(String[] args) throws IOException { ListOfFiles mylist = new ListOfFiles(args); SequenceInputStream s = new SequenceInputStream(mylist); int c; while ((c = s.read()) != -1) System.out.write(c); s.close(); } }Concatenate
utility does is create aListOfFiles
object namedmylist
which is initialized from the command line arguments entered by the user. The command line arguments list the files to be concatenated together.mylist
is used to initialize theSequenceInputStream
which usesmylist
to get a newInputStream
for every filename listed by the user.ListOfFiles implements theimport java.util.*; import java.io.*; public class ListOfFiles implements Enumeration { private String[] listOfFiles; private int current = 0; public ListOfFiles(String[] listOfFiles) { this.listOfFiles = listOfFiles; } public boolean hasMoreElements() { if (current < listOfFiles.length) return true; else return false; } public Object nextElement() { InputStream in = null; if (!hasMoreElements()) throw new NoSuchElementException("No more files."); else { String nextElement = listOfFiles[current]; current++; try { in = new FileInputStream(nextElement); } catch (FileNotFoundException e) { System.err.println("ListOfFiles: Can't open " + nextElement); } } return in; } }Enumeration
interface. You'll see how this comes into play as we walk through the rest of the program.
After the
main
method creates theSequenceInputStream
, it reads from it one byte at a time. When theSequenceInputStream
needs anInputStream
from a new source (such as for the first byte read or when it runs off the end of the current input stream), it callsnextElement
on theEnumeration
object to get the next InputStream.ListOfFiles
createsFileInputStream
objects lazily, meaning that wheneverSequenceInputStream
callsnextElement
,ListOfFiles
opens aFileInputStream
on the next filename in the list and returns the stream. When theListOfFiles
runs out of files to read (it has no more elements),nextElement
returns null, and the call toSequenceInputStream
'sread
method returns -1 to indicate the end of input.
Concatenate
simply echos all the data read from theSequenceInputStream
to the standard output.
Try this: Try runningConcatenate
on thefarrago.txt
andwords.txt
files which are used as input to other examples in this lesson.
![]() ![]() ![]() |
Start of Tutorial > Start of Trail > Start of Lesson | Search |