Java
  Home arrow Java arrow Page 2 - Using Streams in Java
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Using Streams in Java
By: Sams Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 11
    2006-04-20

    Table of Contents:
  • Using Streams in Java
  • Buffered Streams
  • Console Input Streams
  • Data Streams

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Using Streams in Java - Buffered Streams


    (Page 2 of 4 )

    A buffered input stream fills a buffer with data that hasn't been handled yet. When a program needs this data, it looks to the buffer first before going to the original stream source.

    Buffered byte streams use the BufferedInputStream and BufferedOutputStream classes.

    A buffered input stream is created using one of the following two constructors:

    • BufferedInputStream(InputStream)—Creates a buffered input stream for the specified InputStream object

    • BufferedInputStream(InputStream, int)—Creates the specified InputStream buffered stream with a buffer of int size

    The simplest way to read data from a buffered input stream is to call its read() method with no arguments, which normally returns an integer from 0 to 255 representing the next byte in the stream. If the end of the stream has been reached and no byte is available, -1 is returned.

    You also can use the read(byte[], int, int) method available for other input streams, which loads stream data into a byte array.

    A buffered output stream is created using one of these two constructors:

    • BufferedOutputStream(OutputStream)—Creates a buffered output stream for the specified OutputStream object

    • BufferedOutputStream(OutputStream, int)—Creates the specified OutputStream buffered stream with a buffer of int size

    The output stream's write(int) method can be used to send a single byte to the stream, and the write(byte[], int, int) method writes multiple bytes from the specified byte array. The arguments to this method are the byte array, array starting point, and number of bytes to write.


    Note - Although the write() method takes an integer as input, the value should be from 0 to 255. If you specify a number higher than 255, it will be stored as the remainder of the number divided by 256. You can test this when running the project you will create later today.


    When data is directed to a buffered stream, it is not output to its destination until the stream fills or the buffered stream's flush() method is called.

    The next project, the BufferDemo application, writes a series of bytes to a buffered output stream associated with a text file. The first and last integers in the series are specified as two arguments, as in the following SDK command:

    java BufferDemo 7 64

    After writing to the text file, BufferDemo creates a buffered input stream from the file and reads the bytes back in. Listing 15.3 contains the source code.

    Listing 15.3 The Full Text of BufferDemo.java

     1: import java.io.*;
    2:
    3: public class BufferDemo {
    4:   public static void main(String[] arguments) {
    5:     int start = 0;
    6:     int finish = 255;
    7:     if (arguments.length > 1) {
    8:       start = Integer.parseInt(arguments[0]);
    9:       finish = Integer.parseInt(arguments[1]);
    10:     } else if (arguments.length > 0)
    11:       start = Integer.parseInt(arguments[0]);
    12:     ArgStream as = new ArgStream(start, finish);
    13:     System.out.println("\nWriting: ");
    14:     boolean success = as.writeStream();
    15:     System.out.println("\nReading: ");
    16:     boolean readSuccess = as.readStream();
    17:   }
    18: }
    19:
    20: class ArgStream {
    21:   int start = 0;
    22:   int finish = 255;
    23:
    24:   ArgStream(int st, int fin) {
    25:     start = st;
    26:     finish = fin;
    27:   }
    28:
    29:   boolean writeStream() {
    30:     try {
    31:       FileOutputStream file = new
    32:         FileOutputStream("numbers.dat");
    33:       BufferedOutputStream buff = new
    34:         BufferedOutputStream(file);
    35:       for (int out = start; out <= finish;
    out++) { 36: buff.write(out); 37: System.out.print(" " + out); 38: } 39: buff.close(); 40: return true; 41: } catch (IOException e) { 42: System.out.println("Exception: " +
    e.getMessage()); 43: return false; 44: } 45: } 46: 47: boolean readStream() { 48: try { 49: FileInputStream file = new 50: FileInputStream("numbers.dat"); 51: BufferedInputStream buff = new 52: BufferedInputStream(file); 53: int in = 0; 54: do { 55: in = buff.read(); 56: if (in != -1) 57: System.out.print(" " + in); 58: } while (in != -1); 59: buff.close(); 60: return true; 61: } catch (IOException e) { 62: System.out.println("Exception: " +
    e.getMessage()); 63: return false; 64: } 65: } 66: }

    This program's output depends on the two arguments specified when it was run. If you use 4 and 13, the following output is shown:

    Writing:
    4 5 6 7 8 9 10 11 12 13
    Reading:
    4 5 6 7 8 9 10 11 12 13

    This application consists of two classes: BufferDemo and a helper class called ArgStream. BufferDemo gets the two arguments' values, if they are provided, and uses them in the ArgStream() constructor.

    The writeStream() method of ArgStream is called in line 14 to write the series of bytes to a buffered output stream, and the readStream() method is called in line 16 to read those bytes back.

    Even though they are moving data in two directions, the writeStream() and readStream() methods are substantially the same. They take the following format:

    • The filename, numbers.dat, is used to create a file input or output stream.

    • The file stream is used to create a buffered input or output stream.

    • The buffered stream's write() method is used to send data, or the read() method is used to receive data.

    • The buffered stream is closed.

    Because file streams and buffered streams throw IOException objects if an error occurs, all operations involving the streams are enclosed in a try-catch block for this exception.


    Tip - The Boolean return values in writeStream() and readStream() indicate whether the stream operation was completed successfully. They aren't used in this program, but it's good practice to let callers of these methods know if something goes wrong.


    More Java Articles
    More By Sams Publishing


       · This article is an excerpt from the book "Sams Teach Yourself Java 2 in 21 days,"...
     

    Buy this book now. This article is excerpted from chapter 15 of Sams Teach Yourself Java 2 in 21 Days, written by Rogers Cadenhead and Laura Lemay (Sams; ISBN: 0672326280). Check it out today at your favorite bookstore. Buy this book now.

    JAVA ARTICLES

    - Deploying Multiple Java Applets as One
    - Deploying Java Applets
    - Understanding Deployment Frameworks
    - Database Programming in Java Using JDBC
    - Extension Interfaces and SAX
    - Entities, Handlers and SAX
    - Advanced SAX
    - Conversions and Java Print Streams
    - Formatters and Java Print Streams
    - Java Print Streams
    - Wildcards, Arrays, and Generics in Java
    - Wildcards and Generic Methods in Java
    - Finishing the Project: Java Web Development ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek