Home arrow Java arrow Page 4 - Working with Input and Output in Java

Working with Input and Output in Java

This article, the first of three parts, will teach you how the programs you create in Java can interact with different storage devices using a communications system called streams. It is excerpted from chapter 15 of the book Sams Teach Yourself Java 2 in 21 days, written by Roger Cadenhead and Laura Lemay (Sams, ISBN: 0672326280).

Author Info:
By: Sams Publishing
Rating: 4 stars4 stars4 stars4 stars4 stars / 12
April 13, 2006
  1. · Working with Input and Output in Java
  2. · Using a Stream
  3. · Handling Exceptions
  4. · File Input Streams
  5. · File Output Streams

print this article

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

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

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

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.*;
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 2022 of the ReadBytes application. The exception is being thrown by lines 67 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.

blog comments powered by Disqus

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- 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 ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials