Java
  Home arrow Java arrow Page 4 - Working with Input and Output 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

Working with Input and Output in Java
By: Sams Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 6
    2006-04-13

    Table of Contents:
  • Working with Input and Output in Java
  • Using a Stream
  • Handling Exceptions
  • File Input Streams
  • File Output 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


    Working with Input and Output in Java - File Input Streams


    (Page 4 of 5 )

    A file input stream can be created with the FileInputStream(String) constructor. The String argument should be the name of the file. You can include a path reference with the filename, which enables the file to be in a different folder from the class loading it. The following statement creates a file input stream from the file scores.dat:

    FileInputStream fis = new FileInputStream
    ("scores.dat");

    Path references can be indicated in a manner specific to a platform, such as this example to read a file on a Windows system:

    FileInputStream f1 = new
    FileInputStream("\\data\\calendar.txt");

    Because Java uses backslash characters in escape codes, the code \\ must be used in place of \ in path references on Windows.

    Here's a Linux example:

    FileInputStream f2 = new
    FileInputStream("/data/calendar.txt");

    A better way to refer to paths is to use the class variable separator in the File class, which works on any operating system:

    char sep = File.separator;
    FileInputStream f2 = new FileInputStream(sep +
    "data" + sep + "calendar.txt");

    After you create a file input stream, you can read bytes from the stream by calling its read() method. This method returns an integer containing the next byte in the stream. If the method returns –1, which is not a possible byte value, this signifies that the end of the file stream has been reached.

    To read more than one byte of data from the stream, call its read(byte[], int, int) method. The arguments to this method are as follows:

    • A byte array where the data will be stored

    • The element inside the array where the data's first byte should be stored

    • The number of bytes to read

    Unlike the other read() method, this does not return data from the stream. Instead, it returns either an integer that represents the number of bytes read or –1 if no bytes were read before the end of the stream was reached.

    The following statements use a while loop to read the data in a FileInputStream object called diskfile:

    int newByte = 0;
    while (newByte != -1) {
    newByte = diskfile.read();
    System.out.print(newByte + " ");
    }

    This loop reads the entire file referenced by diskfile one byte at a time and displays each byte, followed by a space character. It also displays –1 when the end of the file is reached; you could guard against this easily with an if statement.

    The ReadBytes application in Listing 15.1 uses a similar technique to read a file input stream. The input stream's close() method is used to close the stream after the last byte in the file is read. Always close streams when you no longer need them; it frees system resources.

    Listing 15.1 The Full Text of ReadBytes.java
     1: import java.io.*;
    2:
    3: public class ReadBytes {
    4:   public static void main(String[] arguments) {
    5:     try {
    6:       FileInputStream file = new
    7:         FileInputStream("class.dat");
    8:       boolean eof = false;
    9:       int count = 0;
    10:       while (!eof) {
    11:         int input = file.read();
    12:         System.out.print(input + " ");
    13:         if (input == -1)
    14:           eof = true;
    15:         else
    16:           count++;
    17:       }
    18:       file.close();
    19:       System.out.println("\nBytes read: " + 
    count); 20: } catch (IOException e) { 21: System.out.println("Error -- " +
    e.toString()); 22: } 23: } 24: }

    If you run this program, you get the following error message:

    Error -- java.io.FileNotFoundException: class.dat
    (The system
    cannot find the file specified).

    This error message looks like the kind of exception generated by the compiler, but it's actually coming from the catch block in lines 20–22 of the ReadBytes application. The exception is being thrown by lines 6–7 because the class.dat file cannot be found.

    You need a file of bytes in which to read. This can be any file, though files larger than a few megabytes in size will take a while to finish running. A suitable choice is the program's class file, which contains the bytecode instructions executed by the Java virtual machine. Create this file by making a copy of ReadBytes.class and renaming the copy class.dat. Don't rename the ReadBytes.class file or you won't be able to run the program.


    Tip - Windows users can use MS-DOS in a command-line window to create class.dat. Go to the folder that contains ReadBytes.class and use the following command:

    copy ReadBytes.class class.dat

    Linux users can type the following at a command line:

    cp ReadBytes.class class.dat


    When you run the program, each byte in class.dat is displayed, followed by a count of the total number of bytes. If you used ReadBytes.class to create class.dat, the last several lines of output should resemble the following:

    177 0 1 0 0 0 96 0 99 0 17 0 1 0 25 0 0 0 62 0 15 0
    0 0 6 0 10 0 8 0 12 0 9 0 14 0 10 0 17 0 11 0 23 0 12 0 49 0 13 0
    55 0 14 0 60 0 16 0 63 0 10 0 67 0 18 0 71 0 19 0 96 0 20 0 99 0
    21 0 128 0 23 0 1 0 28 0 0 0 2 0 29 -1 Bytes read: 957

    The number of bytes displayed on each line of output depends on the column width that text can occupy on your system. The bytes shown depend on the file used to create class.dat.

    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