Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Expo on Google News

SYS-CON.TV
Cloud Expo & Virtualization 2009 East
PLATINUM SPONSORS:
IBM
Smarter Business Solutions Through Dynamic Infrastructure
IBM
Smarter Insights: How the CIO Becomes a Hero Again
Microsoft
Windows Azure
GOLD SPONSORS:
Appsense
Why VDI?
CA
Maximizing the Business Value of Virtualization in Enterprise and Cloud Computing Environments
ExactTarget
Messaging in the Cloud - Email, SMS and Voice
Freedom OSS
Stairway to the Cloud
Sun
Sun's Incubation Platform: Helping Startups Serve the Enterprise
POWER PANELS:
Cloud Computing & Enterprise IT: Cost & Operational Benefits
How and Why is a Flexible IT Infrastructure the Key To the Future?
Click For 2008 West
Event Webcasts
Programming with I/O Streams: Part 2
Programming with I/O Streams: Part 2

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
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/ ;

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
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.

About 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.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Latest Cloud Developer Stories
Rackspace Hosting, the service leader in cloud computing, on Thursday announced its acquisition of SharePoint911, an industry leader in SharePoint consulting, training, and "JumpStart" services within SharePoint. The unification of both companies provides capabilities to deliver ...
With Cloud Expo 2012 New York (10th Cloud Expo) now under four months away, what better time to start introducing you in greater detail to the distinguished individuals in our incredible Speaker Faculty for the technical and strategy sessions at the conference... We have techn...
Nimble, the social CRM platform has announced the launch of Nimble 2.0, billed as the “most social” CRM platform on the market today. Nimble was designed entirely with social CRM in mind and is the first social business platform that empowers companies with the ability to get clo...
2011 was a year of rapid adoption for public and private cloud services. Instant and on-demand server provisioning was the driving force behind the massive growth. On top, cloud server templates and script automation simplified application installation for simple and pre-defined ...
"Having been in the IT field for many years, I believe the cloud computing chapter in the industry is an exciting one and I am proud to be a part of it," said National Reconaissance Office (NRO) Chief Information Officer Jill T. Singer Tuesday, as it was announced that she was on...
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON Featured Whitepapers
ADS BY GOOGLE

Breaking Cloud Computing News

CDW Corporation: