Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

Chapter 8 Java I/O Fundamentals

(Note that you’re setting the delimiter and not the pattern that you want to match). The program makes use of a TreeSet<String> to store the read strings. The program reads words from the underlying stream, checks if it is a non-empty string, and adds the lower-case versions of the string to the TreeSet. Since the data structure is a TreeSet, it removes duplicates; remember that it’s a Set, which does not allow duplicates. Further, it is also an ordered data structure, meaning that it maintains an “ordering” of values inserted, which in this case is an alphabetical ordering of Strings. Hence the program correctly prints the words from given text file that contained a limerick.

Byte Streams

In this section, you’ll explore I/O with byte streams. You’ll first learn how to read and write data files, and also how to stream objects, store them in files and then read them back. The class of OutputStream and its derived classes are shown in Figure 8-4; InputStream and its derived classes are shown in Figure 8-5.

 

DataOutput

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

OutputStream

 

 

 

 

 

(interface)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

ObjectOutput(interface)

 

 

PipedOutputStream

 

FilterOutputStream

 

FileOutputStream

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

ObjectOutputStream

DataOutputStream BufferedOutputStream

Figure 8-4.  Important classes deriving from the OutputStream abstract class

 

DataInput

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

InputStream

 

 

 

 

 

 

 

 

(interface)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

ObjectInput (interface)

 

 

 

PipedInputStream

 

 

FilterInputStream

 

 

FileInputStream

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

ObjectInputStream

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

DataInputStream

 

 

BufferedInputStream

 

PushbackInputStream

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 8-5.  Important classes deriving from the InputStream abstract class

Table 8-5 summarizes the important classes of InputStream and OutputStream.

237

Chapter 8 Java I/O Fundamentals

Table 8-5. Important Classes Deriving from the InputStream and OutputStream Classes

 

 

Class name

Short description

PipedInputStream,

PipedInputStream and PipedOutputStream create a communication channel

PipedOutputStream

on which data can be sent and received. PipedOutputStream sends the data and

 

PipedInputStream receives the data sent on the channel.

FileInputStream,

FileInputStream receives a byte stream from a file, FileOutputStream writes a

FileOutputStream

byte stream into a file.

FilterInputStream,

These filtered streams are used to add functionalities to plain streams. The output

FilterOutputStream

of an InputStream can be filtered using FilterInputStream. The output of an

 

OutputStream can be filtered using FilterOutputStream.

BufferedInputStream,

BufferedInputStream adds buffering capabilities to an input stream.

BufferedOutputStream

BufferedOutputStream adds buffering capabilities to an output stream.

PushbackInputStream

A subclass of FilterInputStream, it adds “pushback” functionality to an input stream.

DataInputStream,

DataInputStream can be used to read java primitive data types from an input stream.

DataOutputStream

DataOutputStream can be used to write Java primitive data types to an output stream.

 

 

Reading a Byte Stream

Byte streams are used for processing files that do not contain human-readable text. For example, a Java source file has human readable content, but a .class file does not. A .class file is meant for processing by the JVM, hence you must use byte streams to process the .class file.

The contents of a .class file are written in a specific file format, described in the specification of the Java Virtual Machine. Don’t worry; you’re not going to understand this complex file format, but you’ll just check its “magic number.” Each file format has a magic number used to quickly check the file format. For example “.MZ” is the magic number (or more properly, magic string) for .exe files in Windows. Similarly, the .class files have the magic number “0xCAFEBABE”, written as a hexadecimal value. These magic numbers are typically written as first few bytes of a variable length file format.

To understand how byte streams work, you’ll just check if the given file starts with the magic number “0xCAFEBABE” (Listing 8-7). If so, it could be a valid .class file; if not, it’s certainly not a .class file.

Listing 8-7. ClassFileMagicNumberChecker.java

import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException;

import java.util.Arrays;

//check if the passed file is a valid .class file or not.

//note that this is an elementary version of a checker that checks if the given file

//is a valid file that is written according to the JVM specification

//it checks only the magic number

class ClassFileMagicNumberChecker {

public static void main(String []args) { if(args.length != 1) {

System.err.println("Pass a valid file name as argument"); System.exit(−1);

}

238

Chapter 8 Java I/O Fundamentals

String fileName = args[0];

//create a magicNumber byte array with values for four bytes in 0xCAFEBABE

//you need to have an explicit down cast to byte since

//the hex values like 0xCA are of type int

byte []magicNumber = {(byte) 0xCA, (byte)0xFE, (byte)0xBA, (byte)0xBE}; try (FileInputStream fis = new FileInputStream(fileName)) {

//magic number is of 4 bytes –

//use a temporary buffer to read first four bytes byte[] u4buffer = new byte[4];

//read a buffer full (4 bytes here) of data from the file if(fis.read(u4buffer) != −1) { // if read was successful

//the overloaded method equals for two byte arrays

//checks for equality of contents if(Arrays.equals(magicNumber, u4buffer)) {

System.out.printf("The magic number for passed file %s matches that of a .class file", fileName);

}

else {

System.out.printf("The magic number for passed file %s does not match that of a .class file", fileName);

}

}

} catch(FileNotFoundException fnfe) {

System.err.println("file does not exist with the given file name "); } catch(IOException ioe) {

System.err.println("an I/O error occurred while processing the file");

}

}

}

Let’s first see if it works by passing the source (.java) file and the .class file for the same program.

D:> java ClassFileMagicNumberChecker ClassFileMagicNumberChecker.java

The magic number for passed file ClassFileMagicNumberChecker.java does not match that of a .class file D:\> java ClassFileMagicNumberChecker ClassFileMagicNumberChecker.class

The magic number for passed file ClassFileMagicNumberChecker.class matches that of a .class file  

Yes, it works. The classes InputStream and OutputStream form the base of the hierarchies for byte streams. You perform file I/O, so open the given file as a FileInputStream. You need to check the first four bytes, so you read four bytes in a temporary buffer. You need to compare the contents of this buffer against the sequence of bytes 0xCA, 0xFE, 0xBA, and 0xBE. If the contents of these two arrays are not equal, then the passed file is not a .class file.

In this program, you directly manipulate the underlying byte stream using a FileInputStream. In case you need to speed up the program when you read large number of bytes, you can use a buffered output stream, as in

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName));

Similar to these input streams, you can use output streams to write sequence of bytes to a data file. You can use

FileOutputStream and BufferedOutputStream for that.

239

Chapter 8 Java I/O Fundamentals

After reading this program, didn’t you think that reading an array of four bytes and comparing the contents of the byte arrays was awkward (instead of directly comparing the contents of an integer)? In other words, 0xCAFEBABE is an integer value, and you could read this value directly as an integer value and compare it against the read integer value. For this, you need to use data streams, which provide methods like readInt(), which we’ll discuss now.

Data Streams

To understand how to write or read with byte streams, let’s write a simple program that writes and then reads constant values to a data file (see Listing 8-8). To keep the problem simple, you will write only the values 0 to 9 in the form of the following primitive type values: byte, short, int, long, float, and double.

Listing 8-8.  DataStreamExample.java

import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException;

//A simple class to illustrate data streams; write constants 0 and 1 in different data type values

//into a file and read the results back and print them

class DataStreamExample {

public static void main(String []args) {

// write some data into a data file with hard-coded name "temp.data" try (DataOutputStream dos =

new DataOutputStream(new FileOutputStream("temp.data"))) {

//write values 1 to 10 as byte, short, int, long, float and double

//omitting boolean type because an int value cannot

//be converted to boolean

for(int i = 0; i < 10; i++) { dos.writeByte(i); dos.writeShort(i); dos.writeInt(i); dos.writeLong(i); dos.writeFloat(i); dos.writeDouble(i);

}

} catch(FileNotFoundException fnfe) {

System.err.println("cannot create a file with the given file name "); System.exit(−1); // don't proceed – exit the program

} catch(IOException ioe) {

System.err.println("an I/O error occurred while processing the file"); System.exit(−1); // don't proceed – exit the program

}

//the DataOutputStream will auto-close, so don't have to worry about it

//now, read the written data and print it to console

try (DataInputStream dis = new DataInputStream(new FileInputStream("temp.data"))) {

//the order of values to read is byte, short, int, long, float and

//double

//since we've written from 0 to 0, the for loop has to run 10 times

240

Chapter 8 Java I/O Fundamentals

for(int i = 0; i < 10; i++) {

//%d is for printing byte, short, int or long

//%f, %g, or %e is for printing float or double

//%n is for printing newline System.out.printf("%d %d %d %d %g %g %n",

dis.readByte(),

dis.readShort(),

dis.readInt(),

dis.readLong(),

dis.readFloat(),

dis.readDouble());

}

} catch(FileNotFoundException fnfe) {

System.err.println("cannot create a file with the given file name "); } catch(IOException ioe) {

System.err.println("an I/O error occurred while processing the file"); } // the DataOutputStream will auto-close, so don't have to worry about it

}

}

First, let’s see if it works by executing the program.

D:> java DataStreamExample 0 0 0 0 0.000000 0.000000 1 1 1 1 1.000000 1.000000 2 2 2 2 2.000000 2.000000 3 3 3 3 3.000000 3.000000 4 4 4 4 4.000000 4.000000 5 5 5 5 5.000000 5.000000 6 6 6 6 6.000000 6.000000 7 7 7 7 7.000000 7.000000 8 8 8 8 8.000000 8.000000 9 9 9 9 9.000000 9.000000

Yes, it works. Now, as mentioned earlier, the contents of data files are not human-readable. In this case, you’re writing values 0 to 9 as various primitive type values into the temporary file write named temp.data. If you try to open this data file and see the contents, you won’t be able to recognize or understand what it contains. Here’s an example of its contents:

D:>type temp.data

 

 

 

• •

•?Ç

?•

 

• •

•@

@

• •

•@@

• •

•@Ç

@•

•@á

• •

•@•

@•

 

@• @•

 

A

 

@

 

 

 

 

A•

@"

 

 

 

 

 

 

 

 

The typed contents of the file temp.data look like garbage values because the primitive type values like the integer values 0 or 9 are stored in terms of bytes. However, the type command in Windows tries to convert these bytes into human-readable characters, hence the output does not make any sense. The data will make sense only if we know the format of the data stored in the file and read it according to that format.

241

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]