| By Anil Hemrajani | Article Rating: |
|
| January 1, 1999 12:00 AM EST | Reads: |
12,378 |
Last month's issue (JDJ, Vol. 3, Issue 12) covered the basic concepts of programming with Java's I/O streams, such as the difference between byte and character streams, the various stream classes, the concept of stream chaining and more. We'll conclude the subject this month by looking at some practical uses of these streams.There are so many uses of streams in Java apps that it's almost impossible to imagine all the ways they can be applied. Nevertheless, I'm going to show you several miniature programs that demonstrate some of the ways that Java API streams can be used. We'll also look at a sample (yet robust) application that uses a mixed bag of these classes.
File Input/Output
File programming in Java is easy -- there's a class to open a file for reading and another for writing to an output file. Listing 1 demonstrates a simple copy utility (similar to the MS-DOS "copy" and Unix "cp" commands). The code in Listing 2 initially opens the input and output files, then uses the following code to copy the input file to the output file and keeps a counter for the number of bytes copied:
while ((read = fr.read(c)) != -1)
{
fw.write(c, 0, read);
total += read;
};
Properties
Not surprisingly, the Properties class provides methods for reading from and writing to configuration files. Listing 3 demonstrates how to load a file using the Properties.load() method and how to extract parameters from the configuration file using the getProperty() method. To save to a configuration file, simply use the Properties.save() method.
Executing Programs
Java provides the java.util.Properties class as a facility for working with configuration files similar to the Windows INI file format that contains unique key=value pairs per line as shown in this example:
user=anil
email=anil@divya.com
webPage=http://divya.com/people/anil/ ;
There may be times when you need to invoke command line programs (e.g., Unix sed or ls), pass data to them and read their output. To do this, you have to use the java.lang.Runtime class to start a program and communicate with it via its input, output and/or error streams. The following lines from Listing 4 run the Unix "ls -l" command and obtain the command's input stream in order to read the program's output:
Process p = Runtime.getRuntime().exec( "ls -l");
InputStream is = p.getInputStream();;
Servlet Programming
If you haven't worked with servlets and are still programming using CGI scripts, you're missing out on some cool stuff. Servlets are the server-side equivalent of applets (applets without the GUI). They also make extensive use of input and output streams (or readers and writers) as demonstrated in Listing 5. The following code fragment from Listing 5 reads all the input sent by the client (most likely an HTML form in a Web browser) using the POST method and echoes it back to the client using the output stream:
InputStream is = req.getInputStream();
OutputStream os = res.getOutputStream();
...
while ((c = is.read(b)) != -1)
os.write(b, 0, c);;
Object Serialization
Object serialization allows a developer to save an object and all its nontransient data to an output stream, and then restore it by reading it back in from an input stream. For example, if we have an "Employee&" object that contains three data members - an employee ID, name and salary - and we wanted to save objects for each employee (e.g., John Smith) to a file, we would use code similar to this:
Employee e = new Employee(1, "John Smith", 55000);
FileOutputStream f = new FileOutputStream("JohnSmith.dat");
ObjectOutput s = new ObjectOutputStream(f);
s.writeObject(e);;
To restore the object saved above, we would use code similar to this:
FileInputStream in = new FileInputStream("JohnSmith.dat");
ObjectInputStream s = new ObjectInputStream(in);
Employee e = (Employee)s.readObject();;
Note that the objects that need to be serialized must implement the Serializable interface by using the "implements java.io.Serializable" statement. However, this interface doesn't require any methods to be defined in the implementation class.
Incidentally, RMI (Remote Method Invocation) makes extensive use of object serialization to exchange objects between the RMI client and server.
Working with Streams in Memory
Working with streams in memory is just as easy as working with any other kind of streams. For example, if we modified the program in Listing 1 (Type.java) to work with a java.io.StringWriter instead of a PrintWriter, we could rewrite that code as follows:
StringWriter sw = new StringWriter();
...
while ((read = fr.read(c)) != -1)
sw.write(c, 0, read);
...
System.out.println(sw.toString());
Standard Input, Output and Error Programming
Standard device programming can be accomplished via three static data members of the java.lang.System class: System.in, System.out and System.err. System.out and System.err are of type java.io.PrintStream while System.in is simply a java.io.InputStream. We've already seen a couple of examples of System.out in our listings. Note that, like other classes, these too can be chained to achieve the required goal.
Sample App Using Socket, GZIP, File
and JDBC Streams
Now that we've looked at several miniature programs, it's time to examine a more robust application that uses a mixed bag of the stream/writer classes.
Figure 1 provides a global view of the hypothetical application and is intended to demonstrate how a few lines of Java code can be empowered if the proper TCP/IP network is in place.
A hospital in California and another in Florida connect to their processing center (via sockets) in Virginia so they can relay information about their patients on a daily basis. The protocol used to send the data is simple: the first line contains the hospital name, the second line contains a patient name, and the the remaining lines contain the patient's data (e.g., name, address, medical history).
The complete code for the client-side processing can be seen in Listing 6.
<p align="center"><img
src="../../../~BUSIN~1/~PUBLI~1/IOSTRE~1/figure2.gif" border="1"
width="500" height="380"> </font>
<p align="center"><strong>
The server in the Virginia data center receives the client (California, Florida) data, stores a local copy in a file using GZIP compression, then forwards the same (compressed) data to a medical reporting agency in Europe by using JDBC to store the data in their relational database. Listing 7 shows the complete source code for the server-side processing.
The reporting agency then runs a program (see Listing 8) to view the patient data stored in their relational database. Note that I haven't explained the programs in Listings 6 through 8, hoping that by now you've learned enough about Java streams to follow the code with the help of my comments in the source code.
Writing Custom Stream Classes
Writing your own stream classes is easy - you simply extend the top-level classes (java.io.Reader/Writer or java.io.Filter*) and implement the required methods. To get an idea of how to write your own classes, take a look at the source code for the various descendant classes in the JDK software. If you're using an IDE instead of Sun's JDK to develop Java programs, look around in the IDE's software directories for the JDK source code (e.g., \VisualCafeDbDe\Java\src).
Why would you write a custom class? Most likely because you want to process the data in a certain way when reading or writing it. Take our backup software, BackOnline, for example, which uses 56-bit DES encryption streams when backing up or restoring data. We had to write it because we wanted to use stream chaining and were missing the encryption stream classes since they didn't exist in JDK 1.0.
Summary
By now you should have a good handle on how I/O streams work. Keep in mind that many new APIs (e.g., Media, 2D/3D, Mail) not covered in this article make use of streams. So take a few minutes to explore the various classes in the java.io package and get a thorough understanding of them - it will be well worth your time if you plan to program in Java.
Published January 1, 1999 Reads 12,378
Copyright © 1999 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
More Stories By Anil Hemrajani
Anil Hemrajani is the author of the book titled Agile Java Development with Spring, Hibernate and Eclipse. He is the founder of Isavix Corporation (now InScope Solutions, Inc.), a successful IT services company, and DeveloperHub.com (formerly isavix.net), an award-winning online developer community that grew to over 100,000 registered members. He has twenty years of experience in the Information Technology community working with several Fortune 100 companies and also smaller organizations. He has published numerous articles in well known trade journals, presented around the world, and received and/or nominated for several awards. Anil can be reached via his web site, VisualPatterns.com.
- Kindle 2 vs Nook
- Why IBM’s Server Chief Got Busted
- Is Cloud Computing Like Teenage Sex?
- Industry Experts Discuss the State of Cloud Computing
- Performance Tuning Essentials for Java
- Confessions of a Ulitzer Addict
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- It's the Java vs. C++ Shootout Revisited!
- Cloud Computing Can Revitalize Your Career as Software Developer
- IBM Could "Reinvent" Java: Mills
- Oracle & Cloud Computing: Exclusive Q&A with SVP Richard Sarwal
- A Brief History of Cloud Computing
- Kindle 2 vs Nook
- Cloud CEOs, CTOs & SVPs to Speak at 4th International Cloud Computing Expo
- Why IBM’s Server Chief Got Busted
- Is Cloud Computing Like Teenage Sex?
- Industry Experts Discuss the State of Cloud Computing
- Performance Tuning Essentials for Java
- The Difference Between Web Hosting and Cloud Computing
- Cloud Computing Expo: Exclusive Q&A with Yahoo! SVP Cloud Computing
- Ajax in RichFaces 3.3, JSF 2 and RichFaces 4
- Confessions of a Ulitzer Addict
- My Thoughts on Ulitzer
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- A Cup of AJAX? Nay, Just Regular Java Please
- Java Developer's Journal Exclusive: 2006 "JDJ Editors' Choice" Awards
- The i-Technology Right Stuff
- JavaServer Faces (JSF) vs Struts
- Rich Internet Applications with Adobe Flex 2 and Java
- Java vs C++ "Shootout" Revisited
- Bean-Managed Persistence Using a Proxy List
- Reporting Made Easy with JasperReports and Hibernate
- Creating a Pet Store Application with JavaServer Faces, Spring, and Hibernate
- What's New in Eclipse?
- Why Do 'Cool Kids' Choose Ruby or PHP to Build Websites Instead of Java?
- i-Technology Predictions for 2007: Where's It All Headed?








































