Input and output

xiaoxiao2021-03-06  43

Input and output

This chapter we discuss the input and output of the Java program. Java provides a number of support in I / O, making our work greatly simplified. We will learn to use these support to complete a variety of complex inputs and output.

1. Understand the class inheritance of java.io

First, let's examine the common output output flows provided by Java (Figure 7.1). Due to the large number of classes, there is no new character stream in version 1.1. In Figure 7.2, we have compared character streams and byte streams, which can see inheritance relationships of character flow. Interfaces and abnormal classes are also omitted.

┌BUFFEREDInputStream

├DataInputstream

┌filterInputstream ┼linenumberinputstream

├fileinputstream └PushbackInputStream

├BYTEARRAYINPUTSTREAM

┌INPUTSTREAM - ┼PipedinputStream

│ SEquencyInputStream

│ StringBufferInputStream

│ └ObjectInputStream ┌BUFFEREDOUTPUTSTREAM

│ ┌filteroutputstream┼DataOutputStream

Object┤ ┤Fileoutputstream └printStream

├Outputstream - ┼BYTEARRAYOUTPUTSTREAM

├File ├pipedoutputstream

├FileDescriptor └ObjectOutputStream

├ObjDecstreamClass

├randomaccessfile

└StreamTokenizer

Figure 1.1 Java.IO package common class level map (excluding character flow)

Many input and output classes are included in Figure 1.1 (this does not include the character stream input and output class we have to say on the ground). In order to use them correctly, we must have a big root-based understanding of their functions and relationships.

1.1 byte stream and character stream

The second chapter refers to the Unicode character set and the ASCII character set. The former represents a character with 16 bits, while the 8 bits indicate a character. The symbol of the Unicode character set can be represented by more than the ASCII character set, which can represent the symbols in most languages ​​in the world.

In the JDK1.0x version, only byte stream input and output classes are provided. That is, the data of the input and output is read and written in bytes. This brings difficulties to the operation of some double-byte characters. For example, Chinese characters, use one byte, it is not possible, which makes the Java program have a problem. For example, use a 1.0X version of JDK to develop a text editor, it may happen: Use a clipboard to put the Chinese character to the text domain but cannot enter Chinese character characters to text domains with a keyboard. This is the standard input stream that only receives the first byte of a Chinese character at a time.

The JDK1.1 has been improved for the input and output. In order to increase the corresponding character stream input and output classes for the byte stream input, the programmer can use the appropriate class according to the actual situation.

Character flow I / O has its own benefits. First it can be applied to most of the world in the world, thus bringing convenience to the localization of the Java program. Second, read a character (16-bit) is fast than reading a byte, in general, it can make up for the time overhead of encoding data according to the current language standard, decoding.

The name of the I / O class and the character stream I / O class has its correspondence. The name of the byte input stream class is ending with "InputStream". The name of the character input stream is ending with "Reader". The name of the byte output stream is "OutputStream", and the character output stream of the name is "Writer".

In order to properly link these two streams, two classes were set in the API, which acts as the bridge of the two. InputStreamReader creates a corresponding character stream from byte stream based on a particular coding rule, and Output. StreamWriter reads characters from the character stream according to the coding rules, and transforms them into bytes, and write the word throttle. The correspondence between the two streams is listed below (Figure 7.2). Among them, the left column is a character stream that is arranged in inheritance relationship, and the right side is the corresponding byte stream.

Reader InputStream

├BUFFEREDReader BufferedInputStream

│ └LinenumberReader LineNumberReader

├ChararrayReader ByTearRayinputStream

├InputstreamReader (NONE)

│ └FileReader FileInputStream

├FilterReader filterInputStream

│ └PushbackReader PushbackInputStream

├pipedreader pipedinputstream

└StringReader StringBufferInputStream

Write OutputStream

├BUFFEREDWRITER BUFFEREDOUTPUTSTREAM

├ChararrayWriter ByteArrayoutputstream

├OutputStreamWriter (NONE)

│ └filewriter fileOutputStream

├FilterWriter FilterOutputStream

├PrintWriter PrintStream

├pipedwriter pipedputstream

└StringWriter (NONE)

Figure 1.2 correspondence between character flow and byte stream

In addition, in the 1.1 version of the API, the classes already existing in some 1.0x versions have also been tiny, mainly because there is an error in the conversion of class and characters. As the following constructor and method are marked as outdated:

Sting DataInputStream.readline ()

InputStream runtime.getlocalizedInputStream (InputStream)

OutputStream runtime.getlocalizedOutputStream (OutputStream)

StreamTaikenizer (InputStream)

String (Byte Ascii [], int hibyte, int offset, int count)

String (byte ascii [], int hibyte)

Void string.getbytes (int srcbegin, int srcend, byte dst [], int dstbegin)

In addition, the following constructor and method are added:

StreamTokenizer (Reader)

Byte [] String.getbytes ()

Void throwable.printStackTrace (PrintWriter)

When programmers use old API programming, you can use

Javac -DepRecation (file name)

To compile, this compiler will give more detailed warning information. Programmaker can find new documents based on this information to learn about the alternatives to the new version.

The examples of this chapter are written in accordance with the 1.1 version of the API.

1.2 Classification of input and output classes

The classes in the java.io package have each division of labor, roughly can be divided into the following categories: Document I / O: There are three types. For byte streams, including the fileinputstream class that flows files as the source as a source; files the file as a FileoutPutStream class that streams the file; if you want to access the file, read, data in any location of the file Then you can use the RandomaccessFile class. Character classes have FileReader and FileWriter classes. They correspond to the first two byte streams.

In addition, two classes are related to file access, exactly that their functions are more frequently managed. They are the File class to access the file or directory; FileDescriptor encapsulates the operating system to track information accessed.

Memory buffer I / O: Byte flow class has a ByteArrayInputStream class, converts the byte array into input streams, is created from a string, with the ByTearrayInputStream isoform, and the help is also classified. Accordingly, the character stream has ChararrayReader, CharaRrayWriter, StringReader, and more than one StringWriter is used to write strings.

Some of the remaining classes can access data in different ways. In byte flow classes, DataInputStream and DataOutputStream are different because they can perform differently in different types of objects in the stream; ObjectInputStream and ObjectOutstream can read and write several complete objects in selected format, but require the object to be operated Implement the serializable interface; BufferedInputStream and BufferedOutputStream can buffer traffic data, implement similar to "pre-input", "slower output" function; LINENUMBERINPUTSTREAM tracks the number of rows in the input stream; PusthbackInputStream provides a "push back" stream, from this After reading the data in the stream, you can also put it back; the PrintStream class provides a number of overloaded methods to simplify the output. The corresponding character stream can be isolated from the corresponding relationship of Section 7.1.1.

In addition to the above classes, Java has special I / O-pipe I / O classes. They are specially prepared for thread communication. The pipe provides an automatic synchronization mechanism to prevent data confusion in thread communication.

The letter to believe that the reader has been known to the functions of each I / O class. Here, there are many classes in the filter I / O promotion Java.IO package, which are derived from FilterInputStream or FilterOutputStream (see Figure 7.1). In the character stream, there are similar classes, but it is not like the byte stream class to derive it from a public filter parent class.

The class object formed by the filter is read from a stream, writes to another, just like a stream is filtered to generate another stream. The filter can be used in conjunction, that is, the "filtration" flow can be "filtered" by other filters, the commonality of the filter type is:

(1) Construction of parameters with and album, and input flow flow, output filter output flow;

(2) No obvious source / purpose restrictions;

(3) The content of the stream is "how much" has not changed, and only the nature changes slightly.

The reader may wish to understand the filter I / O class with its subclasses with these standards, and verify in later examples.

2 input flow and output stream

Byte Entercast InputStream and byte output stream OutputStream is two abstract classes. They have founded a wide range of byte inputs and output streams in java.io bags. Because it is an abstract class, they cannot be instantiated (that is, the object cannot be obtained), but their methods can be inherited or rewritten by derived classes. For character streams, the corresponding streams are Reader and Writer. Because their methods correspond to the InputStream and OutputStream, just change the operation of the byte to the character's operation, this is no longer repeated. However, for the reader to have a basic understanding of their correspondence, the reader is included in the end of the READER class at the end of this festival.

InputStream is shown below:

■ Public Abstract Int Read () THROWS IOEXCEPTION

■ Public int in (Byte B []) THROWS IOEXCEPTION

■ Public int in (Byte B [], int Offset, int LENGTH) THROWS IOEXCEPTION

The function is read from the input stream. This approach has several overloaded forms that can be read one byte or a set of bytes. Returns -1 when you encounter a file. The OFFSET in the final form refers to the space that starts the result in B [] from the origin of the OFFSET, Length is the length.

■ Public int available () THROWS IOEXCEPTION

How many bytes readable in the input stream. Note that this method is not necessarily valid for the allocation of the INPUTSTREAM, sometimes there is an error result returns zero-byte.

■ Public void close () THROWS IOEXCEPTION

Turn off the input stream and release the resource.

■ Public Boolean Marksupperted ()

Returns the Boolean value, indicating whether this stream is tagged.

■ Public Synchronized Void Mark (int ready)

Mark the current stream. Its parameters illustrate how many bytes can be read before marking failure, which typically sets the stream buffer size.

■ Public synchronized void reset () THROWS IOException

Return to the last time to make a marker.

■ Public long Skip (long n) throws orenception

Take a few bytes from the input stream. The return value is the number of bytes actually skipped.

We also need to explain it for "Mark". The input stream provides "tag" mechanism to enable people to record certain locations in the stream and can repeat the part of the content. Support "Mark" must be required to have a certain size buffer, stored some data, ie data from the markpoint to the current location. When this buffer is full of overflow, we cannot track data from the previous mark, which is called "tag failure". If you want to use RESET () to return to a failed mark, an input and output exception will occur.

The method of OutputStream is as follows. Each method may throw an input and output anomaly (Throws oxtception).

■ Public Abstract Void Write (INT B)

■ Public void write (byte b [])

■ Public void write (byte b [], int offset, int ing

These three overload forms are used to write data to the output. Each of the particulars of each is unwillingly, the reader can control according to the foregoing read () method.

■ Public void flush ()

Clear the buffer to output all the data that has not been written in the buffer. To inherit the OutputStream class, this method must be rewritten because the method in OutputStream does not do any physical work.

■ Public void close ()

Turn off the output stream and release the resource.

These methods mentioned above, there will be many applications in the following sections, readers can take them according to instances. A list of ways of the Reader class.

Constructor:

■ protected reader ()

■ protected reader (Object Lock)

method:

■ Public int ready () throws oException

■ Public int in (Char Cbuf []) THROWS IOEXCEPTION

■ Public Abstract Int Read (Char Cbuf [], int Off, int LEN) THROWS IOEXCEPTION

■ Public long Skip (long n) THROWS IOEXCEPTION

■ Public Boolean Ready () throws ioException // Judgment flow is not read

■ Public Boolean Mark (int tentaheadlimit) THROWS IOEXCEPTION

■ Public void reset () THROWS IOEXCEPTION

■ Public Abstract Void Close () THROWS IOEXCEPTION

3 file I / O

In this section, we will discuss the method and use of the File, FileInputStream, FileOutputFile classes.

3.1 A file I / O instance

Let us use an example to demonstrate the input and output of the file (Example 7.1). This example is listed in Figure 7.3.

Example 1 FileIodeMo.java.

1: Import java.io. *;

2: Import java.lang. *;

3:

4: Public class fileiodemo {

5: public static void main (string args []) {

6: TRY {

// Create an input and output flow

7: FileInputStream Instream = New FileInputStream ("text.src");

8: fileoutputstream outstream = new fileoutputstream ("text.des");

// read and write output flow

9: boolean EOF = false;

10: While (! EOF) {

11: INT C = instream.read ();

12: IF (c == - 1) EOF = true;

13: Outstream.write ((char) c);

14:}

15: instream.close ();

16: Outstream.close ();

17:} catch (filenotfoundexception ex) {

18: System.out.println ("ERROR FINDING THE FILES");

19:} catch (ioexception ex) {

20: System.out.println ("IOEXCEPTION OCCURED.");

twenty one: }

// Get file management information

22: File File = New File ("text.des");

23: System.out.println ("Parent Directory:" File.getParent ());

24: System.out.println ("PATH:" File.getPath ());

25: System.out.println ("File Name:" file.getname ()); 26: Try {

// Create a randomaccessfile object so that you can read and write at random. "rw" represents readable can be writable

27: randomaccessfile rafile = new randomaccessfile ("text.des", "rw");

/ / Pointer to the file header

28: Rafile.seek (0);

29: Boolean EOF = FALSE;

30: System.out.println ("The Content from Very Head:");

// read the file

31: While (! EOF) {

32: INT C = rafile.read ();

33: IF (c == - 1) EOF = true;

34: Else System.out.print ((char) c);

35:}

// The next two lines put the read finger to the third byte

36: rafile.seek (0);

37: rafile.skipbytes (3);

38: System.out.println ("/ NTHE POINTER'S POSITION:" Rafile.GetFilePointer ());

39: System.out.println ("THE Content from Current Position:");

40: EOF = false;

41: While (! (! EOF) {

42: INT C = rafile.read ();

43: IF (c == - 1) EOF = true;

44: Else System.out.print (CHAR) C);

45:}

/ / Force all content in the buffer

46: System.out.flush ();

47: rafile.close ();

48:} catch (ioexception ex) {

49: System.out.println ("RandomaccessFile Cause IOException!");

50:}

51:}

52:}

Example 1 The results of the operation are as follows:

(slightly)

In order to fully display the role of the class associated with file I / O, there are some redundant things in our example. Our program is located in the C: / BookDemo / CH07 path (see Example 7.1 line 7), this path has a child as a text, where there is file text.src. Run this program, create a new file text.des in C: / BookDemo / CH07, text.src's content is written to this file. The following segment describes the partial management information of the file in the File class. Then we used RandomaccessFile and tried the document read and write in the specified location.

The Sytem.Flush () statement of line 46 cannot be omitted, the reader may wish to drop it. You will find that some of the output information doesn't know where to go. In fact, the role of Flush () is to output all the data in the buffer. After we output flow output, some output streams (the flow of buffers) simply written the data into the buffer, will not write immediately Go to the destination of our request. If it is not as forced as in the example, some data can be output before the program ends.

The careful readers may ask: Why didn't I use ReadomaccessFile to read files for the first time, there is no flush ()? Doesn't it contradict? It turns out that System.out is the object of the PrintStream class (About the content in the buffer after printstream, so many places do not have to add this feature of .PrintStream, which can be removed when creating its objects (Disable) This program is used in IOException and FilenotFoundException. The latter is derived from the former, so if all TRY, Catch, Catch in the program, while the main () method starts plus throws ioException, which can be. But this is not good to distinguish a variety of different abnormal conditions, even if we can't find the text.src files we need, there will be no information display. This is undoubtedly a bad programming style. So we advocate each abnormality separately This can be mastered in this way.

3.2 File input and output class library support

Below we will introduce the various classes used in Example 1 one by one.

1.file class

There are three constructor of the FILE class. Create an instance according to the file name, file path and file name, file object (directory) and file name, respectively. which is:

■ Public File (String Path)

■ Public file (String path, string name)

■ Public File (File Dir, String Name)

In addition to the examples used in Example, there are many methods, only listed below:

■ Public Boolean Exists () Decision Documentation Present

■ Public boolean canread () determines if the file is read

■ Public long length () Returns the length of the file

■ Public Boolean Mkdir () Creates a directory

■ Public Boolean RenameTo (file dest) file rename

Among them, the three methods may throw I / O abnormalities.

2.FileInputStream class

It is file input stream class

Three constructed functions:

■ Public FileInputStream (String FileName) throws filenotfoundexception

■ Public FileInputStream (File File) Throws FilenotFoundException

■ Public FileInputStream (int FD) throws filenotfoundexception

The three constructor creates a file input stream according to the file name, file object, and file descriptor, respectively. The first one is used in the example.

method:

READ (), SKIP (), Available (), and close () rewrite the same name method of the abstract class InputStream, and the function is as mentioned earlier. There are also:

■ Public Final Int getFd ()

Returns the corresponding file descriptor.

■ Protedted Void Finalize () THROWS IOException

Turn off the input stream and collect the free memory space.

Now we have to introduce the file descriptor class FileDescriptor. This class is used to access the file descriptor (also known as a handle) maintained by the operating system. But this class cannot access a lot of information. It only provides two methods, namely valid () to determine if the file descriptor is valid; SYNC () is used to synchronize the system buffer.

3.FileOutputStream class

File output stream. Three constructor, its parameters, return values, and exceptions correspond to FileInputStream. Write (), close () method rewrites the same name method for OutputStream. GetFd () is similar to the Finalize () function with the InputStream.

4. ReadomaccessFile class This class is used to random access files.

There are three constructor:

■ Public randomaccessfile (String FileName, String Mode) throws oException

■ Public RandomaccessFile (int FD) THROWS IOEXCEPTION

■ Public RandomaccessFile (File File, String Mode) throws oException

As can be seen, we can use the file name to read the write mode, file descriptor, and file objects to create its objects. The read and write mode is read-only with "R", "RW" means readable and written, and so on. Readers who have used C language should not be unfamiliar.

There are many members of this class. In addition to rewriting the inputstream's read () method, you can also read, write a Boolean value, one byte, an integer ... and other objects. These methods are not overwritten and throw IOEXCeption. The method name is "Read" plus type name (the first letter of type name), and the write method is called "Write" plus type name. Such as

Readint () reads a whole number

WriteDouble () writes a double precision floating point number

Wait. There is also a file pointer operation, such as SkipBytes (INT N), etc.

With the support of these classes, it is easy to process file input and maintenance files.

4 memory buffer

Memory buffer I / O, refers to byterrayinputstream and ByteArrayoutputStream classes. In addition, StringBufferInputStream is similar to byteArrayInputStream usage. For the word stream, it is not used, and they are similar to byte streaming.

4.1 Example

Like the same section, we still look at an example (Example 2)

Example 2 ByteArrayiodeMo.java

1: Import java.io. *;

2:

3: Public class byterrayodemo {

4: public static void main (string args []) throws oException {

String s = "THIS A TEST";

5: Byte buffer [] = s.getbytes ();

6: ByteaRrayoutputStream ByteArrayout = new byteArrayoutputStream ();

7: for (int i = 0; i

8: BYTEARRAYOUT.WRITE (Buffer [i]);

// Create byte input stream by byte arrays

9: ByteaRrayinputStream Instream = New

ByteaRrayinputStream (ByteArrayout.tobyteaRray ());

// Read and write

10: Boolean EOF = FALSE;

11: While (! EOF) {

12: INT C = instream.read ();

13: IF (c == - 1) EOF = true;

14: Else System.out.print ((char) c);

15:}

16: System.out.println ("/ NTHE'WRITO 'METHOD CAN Produce Same Results);

// Write the Writto () method with ByteaRrayoutputStream

17: ByteArrayout.writeto (System.out);

18: ByteArrayout.close (); // Available () with reset ()

19: System.out.println ("/ NTHE BUF OF INSTREAM HAS THE Length (Before

SESET): " Instream.availa ());

20: instream.reset ();

21: System.out.println ("/ NTHE BUF OF INSTREAM HAS THE Length:" Instream.available ());

22: Instream.Close ();

twenty three: }

twenty four:}

The operation result of the program: (omitted)

This example seems to be relatively simple. Let's write the contents of the byte array into a byte array output stream object. Then, enter the flow object read data with a byte array, and then output with System.out. The program shows the role of the Writto () method. In addition, we are still in reset (), after two guilt, please pay attention to the different results generated by the two methods. This example is primarily used to demonstrate some of the methods of the byte array I / O.

4.2 Buffer I / O class library support

I have seen an example, let's introduce the associated class.

1.byteArrayInputStream class

This class is used from one

The byte array acquires input data.

It has two constructor:

■ Public ByteArrayinputStream (Byte Buf [])

Create a corresponding input stream by byte arrays.

■ Public ByTearRayinputStream (Byte Buf [], int offset, int ing

The starting point from the byte array creates a input stream for the OFFSET long for Length.

Member variables:

Protected byte BUF [] Data Buffer

Current location in the Protected Int POS buffer

Protected int COUNT number of bytes in the buffer

The members of this class are synchronous (SYNCHRONIZED).

■ Public synchronized int ■ ()

Read a byte.

■ Public synchronized int in (Byte B [], int offset, IntrLength)

Read multiple bytes, the return value is generally the number of bytes read. But returning -1 when reading at the end.

■ Public synchronized long Skip (long n)

Skip n bytes. If the return value is not equal to N, it may be to meet the end.

■ Public synchronized int available ()

Ask the number of bytes in the buffer.

■ Public synchronized void reset ()

This pointer is reset to the beginning of the input stream. Note that this reset () is different from the features in the InputStream. It doesn't work on tags.

2.ByteArrayoutputstream class

This class is used to write data into the byte array (buffer).

Constructor:

■ Public ByteArrayoutputStream ()

■ Public ByteArrayontPut Stream (int size)

Where SIZE specifies the initial size of the buffer (it can grow).

Member variables:

Protected byte BUF [] buffer

Protected int COUNT buffer size

method:

■ Public Synchronized Void Write (INT B)

Write a byte.

■ Public synchronized void write (byte b []te b [], int offset, int lay

Write the buffer from the array b from a part of the LENGTH.

■ Public Synchronized Void Writeto (OutputStream Out "Write the buffer content to another output stream OUT.

■ Public synchronized void reset ()

The pointer is set to the buffer start. Of course, it will be written in the future, and the original content is clear from the start position of the buffer.

■ Public syschronized byte [] TobyTearray ()

Return the buffer content as a byte array.

■ Public int size ()

Current buffer size.

■ Public string toString ()

■ Public String Tostring (int hibyte)

Transform the buffer content into a string. Where hibyte refers to the value of the character (usually 8-bit ASCII characters) to 16-bit Unicode values, the highest value.

3.StringBufferInputStream class

Its constructor is parameter with a string, prototype:

■ Public StringBufferInputStream (String S)

The remaining members variables and methods are the same name of ByTearRayinputStream and the basic functions are the same.

The commonality of these three classes is a space in memory to do an I / O buffer, so that the buffer I / O class is called.

5 filter I / O

There are many categories involved in this section, but we can introduce a few examples one by one.

In the first quarter, we have talked about the characteristics of some filter classes. The filter can be "connected", that is, a data stream is filtered, and the result can be filtered again. We can use any of the methods in such a string of filters to complete some special operation. About this point in the second example is explained more clearly.

5.1: I / O of various types of data

The first example (Example 3) demonstrates the input output of various types of data.

Example 3filteriodemo1.java.

1: Import java.io. *;

2: public class filteriodemo1 {

3: public static void main (string args []) throws oException {

/ Sawer filter

4: BufferedoutputStream bufout =

5: New BufferedOutputStream (New FileoutputStream ("text.txt");

6: DataOutputStream DataOut = New DataOutputStream (bufout);

// write various data with the DataOutputStream class

7: DataOut.writeBoolean (TRUE);

8: DataOut.writechar ('a');

9: DataOut.writeint (1);

10: DataOut.writedouble (3.3);

11: bufout.close ();

12: DataOut.close ();

13: BufferedInputStream BUFIN =

14: New BufferedInputStream (New FileInputStream ("Text.txt");

15: DataInputStream DataIn = New DataInputStream (bufin);

// read various data by DataInputStream

16: System.out.println (Datain.Readboolean ());

17: System.out.println (DataIn.Readchar ());

18: System.out.println (DataIn.Readint ());

19: System.out.println (DataIn.Readdouble ()); 20: bufin.close ();

21: Datain.Close ();

twenty two: }

twenty three:}

The operation results of Example 3 are as follows: (omitted)

The above example demonstrates the use of DataInputStream, DataOutpurstream, BufferedInputStream, and BufferedOutputStream. There is only one method main () in the program.

At the beginning of the method, we instantiate the BufferedoutputStream class to get the object bufout. Note that the ultimate destination of our data output is the file "text.txt". In order to be able to use the bufferedoutputstream's slowout (put the output content to buffer, then large block output) function, we add a filter to the file output to form:

Data → Filter Object BUFOUT → File Output Flow

In this way, we write data with Dataout, you can write all types of data into file text.txt.

The latter half of the program is almost the release of the first program. We also add a filter on the input stream to operate the input stream with a filter method.

Since BufferedputStream and BufferedInputStream do not provide new methods, this example may make readers to generate an illusion, as if only the outermost layer (closest to "data") can be manipulated. This is not the case, we will explain this in the next example.

What we want to explain is that if we read the data, what will the read method and write? Readers can experiment with their own. If we put

DataIN.Readboolean () DataIN.Readchar ()

The result of the read is incorrect (note that the read is not character 't'), and various types of data stored formats are different. Although we got the results shown in Figure 7.4, if you look at the text.txt with the Type command, you will see different outputs. Therefore, don't mix the output of the program and the internal storage of the program as a talk. When using Datai / O, you should have a number of data for the data you want to read. DataInputStream does not count the integers you need from a bunch of data.

5.2 Filter Class Family

Let's introduce the filter class that appears in Example 1. First introduce their parent class FilterInputStream and FilterOutputStream.

1.FilterInputStream class

This is an abstract class. It is the parent class of all filters input class, providing a method of creating another input stream from an input stream.

Constructor:

■ Public FilterInputStream (InputStream IN)

An input stream constructs a filter input stream.

method:

Rewinding the same name method of InputStream, no new approach is provided.

2.FilterOutputStream class

Compared with the FilterOutputStream, a method of creating another output stream from an output stream.

Constructor:

■ Public File OutputStream (OutputStream Out)

Create a filter output stream by the output stream.

method:

Renown the same name method of OutputStream.

3.BUFFEREDInputStream class

From this class, let's introduce the filter subclasses used in Example 7.3. The BufferedInputStream class provides a "pre-entered" feature that puts the input data in its buffer, and submits the larger block data in its appropriate time.

Constructor:

■ Public BufferedInputStream (InputStream IN)

■ Public BufferedInputStream (Inputsteam IN, int size) where the size refers to the buffer size.

method:

Rewrite the method of the parent class. Skip (), Available (), Mark (), and reset () are synchronous (SYNCHONIZED).

4. BufferedoutputStream class

Provide a "loose output" function, after the output data is temporarily stored, at the appropriate time.

Constructor:

■ Public BUFFEREDOUTPUTSTREAM (OutputStream Out)

■ Public BufferedOutputStream (OutputStream Out, int size)

method:

■ Public Synchronized Void Write (INT B) THROWS IOException

■ Public synchronized void write (byte b [】, int tent, intlene) throws oException

■ Public Synchronized Void Flush () THROWS IOEXCEPTION

The above method rewrites the method of the same name of the parent class.

In the Bufferedi / O class, there are some Protect type members variables, which are about buffers and tags, which are not listed here.

5. DataInput interface and DataoutPUT interface

To introduce the Data I / O class, you must introduce the DATA I / O interface.

The purpose of the DATA I / O class is to write a specified data object from the stream or write the specified data object in the stream. A stream can be a pure word stream, or a number of types of data can also be included. The DataInput interface and the DataOutput interface provide methods of extracting and writing data from the stream. The method used to read is unfained in addition to individual, and the method of writing is often the parameter of the data written. The name of the method is also very good, that is, "Read" or "Write" rear type name, such as readint (), readunsignedbyTe (), WriteInt (), WriteunSignedByte (), etc.. This causes the method to throw I / O abnormalities. Generally speaking, throwing EOFEXCEPTION (the subclass of IOEXCEPTION) when reading the file, and other errors occur when reading and writing IOException.

In addition to the names mentioned above, there are several ways in the Data I / O interface:

■ Public Abstract Void ReadFully (Byte Buffer "

Read all data to the buffer [] array. The system is in a blocking state.

■ Public Abstract Void ReadFully (byte buffer [], int offset, int lay

Read the data to the array buffer [] starts from OFFSET to a place for Length.

■ Public Abstract Int SkipBytes (int N)

Skip the number of specified bytes. The return value is the number of bytes that actually skip.

■ Public Abstract String Readline ()

Read a line of data.

In addition, there are three overload forms of the Write () method we have already familiar with.

6. DataInputStream class

After introducing two data I / O interfaces, the data I / O stream is more simple. The DataInputStream class implements the DataInput interface, and all members of this interface is implemented. In addition, there are two READ () methods:

■ Public Final Int Read (Byte B [])

■ Public Final Int Read (Byte B [], INT Offset, Int Length)

Rewind the same method of the FilterInputStream.

DataInputStream has only one constructor. Like all filters, the parameters of this constructor are an object of InputStream.

7.DataOutputStream class

We are very familiar with the members of this class. In addition to the method of implementing the DataoutPut interface, it is a flush () method. Write () with flush () rewrites the same name method for the FilterOutputStream class.

Now we can go back and look at this example 7.3, confirming the content you have told. One of this example is that one of the "connections" demonstrated, and the other is to introduce the corresponding class.

5.3 Case 2: Line number and "Push Back" stream

In the following example (Example 4), we will further understand the connection problem of the filter. The front example basically uses byte streams, this example uses a character stream.

Example 4 Filteriodemo2.java.

1: Import java.io. *;

3: Public class filteriodemo2 {

4: public static void main (string args []) throws oException {

5: string s = "this is a multi-line string./n it is / named to demo filterio./N";

6: char Array [] = new char [s.ley ";

7: for (int i = 0; i

8: Array [i] = S.Charat (i);

// Create a word stream, serial filter

9: ChararrayReader Charreader = New ChararrayReader (Array);

10: PushbackReader Pushreader = New PushbackReader (CharReader);

11: LINENUMBERREADER LINEREADER = New LinenumberReader (PushReader);

12: String line;

// read the word stream, plus trial output

13: While ((line = lineReader.readline ())! = Null) {

14: System.out.println (LineReader.getLinenumber () ":" line);

15:}

/ / Pointer to the beginning

16: Try {pushreader.reset ();} catch (ooException e) {}

// read the word stream, push it back every one '/ n'

17: Boolean EOF = FALSE;

18: boolean met = false;

19: While (! EOF) {

20: INT C = pushreader.read ();

21: IF (c == - 1) EOF = true;

22: Else IF ((char) c == '/ n') &&! Met) {met = true; pushreader.unread (c);}

23: Else Met = false;

24: IF (c! = - 1) System.out.print ((char) c);

25:}

26: System.out.flush ();

27: pushreader.close ();

28: CharReader.close ();

29: LineReader.close ();

30:}

31:}

The result of the program is as follows: (omitted)

The function of this example is: Give a string to the line number after the line number; repeat each newline character once, that is, add a blank line each time you wrap. This example uses character stream I / O, demonstrates several classes: CharaRrayReader, PushbackReader, LinenumberReader. In addition, we can also review several streams mentioned earlier. PushbackReader, as the name suggests is the stream of streaming of data "push back". We use it to realize the repetition of the charter - "Push back" as long as you finish reading, you can read it again next time. LINENUMBERREADER can track the number of entered rows and use it to implement plus trial output.

Now let's explain the program. In the 5th line, a string S is defined in the main () method. Among them, there are three newlines '/ n'. Then create a byte array array [], and assign values ​​for it in the next FOR loop (line 7, 8). A memory buffer input stream is created with this as a parameter. This is the source point of our a stroke filter. Note that Array is not an input stream, and the corresponding CaarRayReader is not a filter.

Now consider using a filter. Can be selected according to the features we want. Since we want to quoter, it is clear that it is best to read data. BufferedReader's readline () method is exactly what we need. () The method is originally a method of DataInputStream class, but it has been out of time in version 1.1. Details have been explained in the first quarter. Here you can warn information when using DataInputStream but compile.) We can Reading a row, you can also accumulate the number of lines above a variable. Of course, an off-the-shelf class and the present method can also be utilized - select the LINENUMBDRREADER class and its getLineNumber () method. Since the LineNumbDRreader itself is a subclass of the BuffredReader class, you can use it directly to read data by line, and you don't have to introduce the BufferedReader class. In order to repeat the write backpack, the PushbackInputStream class and its unread () method can be used.

The following tasks are stringing them, as shown in the example, can put some of the "output" as the next "input". The first While loop (line 13 to 15 lines) is very simple; read a line of information, obtain its line number, then some output.

The work of the second While loop (line 19 to 25 lines) is to rewrite the operator. We use PushReader to read data. The Boolean EOF is identified whether the input is ended, and the MET is used to identify if the petal line is pushed back. When the input is not over, it will not "push back" every time you read it, it will not be "push back", and it is guaranteed that the newline character is only repeated.

As mentioned earlier, any of a string filter can operate data, regardless of the first one or the most, any one.

Since we used the Print () method to output characters, there may be some data at the end of the program, in the buffer, not written to the screen. So we added a flush () method forced to display on the screen.

The wandering will be closed (line 27 to 29) is a good editor. Although Java's "garbage collection" system can recover the abandoned resources, we should consciously clean the "battlefield" and take the initiative to recover the resources.

5.4 class library support

The new classes that appear in this case 7.4 will be described in detail below. One thing to explain is that the inheritance relationship between the character stream I / O class and the byte stream I / O class is not one or one. For example, PrintStream in the byte stream I / O is the subclass of FilterOutputStream, and the corresponding character stream printWriter is a subclass of the Writer class. Therefore, strictly said PrintWriter is not a filter class. However, in order to be able to study these classes, we don't want to see this difference, but in accordance with the inheritance of the byte stream I / O, the corresponding character stream I / O class also views the filter class. PushbackReader class

Two constructor:

■ Public PushbackReader (Reader In, INT Size)

Create a buffer size for a PushbackReader object.

■ Public PushbackReader (Reader IN)

Creating a buffer size is a PushbackReader object for a character.

method:

■ public int in ()

■ Public Int Read (Char CBUF [], INT Offset, INT LENGTH)

Read data.

■ Public Void Unread (int CH)

Roll back a character. The I / O exception is thrown when the abnormality of the buffer is full or other input output.

■ Public int avaliable ()

Returns the number of internal bytes of buffers.

■ Public Boolean Marksupported ()

Confirm that the input stream supports the tag function.

Read (), unread (), and Available () may throw IOEXCEPTION.

2.LinenumberReader class

Two constructors, similar to PushbackReader.

The prototype of the method is listed below, where we are already familiar, there is no explanation.

■ Public int ready () throws oException

■ Public Int Read (Char Cbuf [], int offset, int length) THROWS IOEXCEPTION

■ Public void setLinenumber (int LineNumber)

Set the line number.

■ Public int getLinenumber ()

Read the line.

■ Public long Skip (long n) THROWS IOEXCEPTION

■ Public int available () THROWS IOEXCEPTION

■ Public Void Mark (int tentaheadlimit) throws oException

Mark in the current position. Since then the ReadaheadLimit characters have become invalid.

■ Public void reset () THROWS IOEXCEPTION

Return to the previous mark.

3.PrintStream class and PrintWriter class

The PrintStream class is a non-negligible member in the filter class. The most basic standard output is to use it - the SYSTEM.out variable we use is the PrintStream instance. The corresponding character stream is the PrintWriter class.

PRINTSTREAM has two constructor (marked in the new version of the API):

■ Public PrintStream (OutputStream Out)

■ Public PrintStream (OutputStream Out, Boolean Autoflush)

Among them, when autoflush is set to True, whenever the output encounters a newline, the content of the buffer is enforced all output, as in calling a Flush (). But pay attention to that if there is no newline, there will be data "" in the buffer.

Method (It is familiar to explain):

■ Public void Write (int b)

■ Public Void Write (Byte B, Int Offset, INT Length)

■ Public void flush ()

■ Public void close ()

■ Public void print (Object Obj)

This method function is very powerful, it can output any object without having to mention it. In addition, the Print () method has many overloaded forms, that is, there are multiple parameters. They are string, character arrays (CHAR []), Char), Integer (int), long integer (long), floating point number (FLOAT), Double-precision floating point number (Double), Boolean ). Among them, the output () method of multiple units () is output (also referring to string and char []) is a synchronization method.

■ Public Void Println () outputs a newline.

■ Public Synchronized Void Println (Object Obj)

The PrintLn () method has 9 heavy load forms, almost the release of the print () method. The only difference is that the println () method is synchronized.

■ Public Boolean Checkerror ()

Check what errors during output, if available, return true values. As long as there is an error in the output stream, the call after the error will return to the true value of the CHECKERROR ().

The PrintWriter class is described below.

As mentioned in the second section, PrintWriter is the JDK1.1 version of the character stream I / O corresponding to byte stream I / O. However, in order to maintain compatibility, the original class has almost no change. In addition, the need for debugging, the PrintStream class is preserved, and the member variable in the System class is Out, Err is still as its object. However, PrintWriter is used in most output than PrintStream. So the 1.1 version of the API recommends that the newly developed code uses the PrintWriter class, and the two constructor of the PrintStream class are marked as outdated. Thus, although the use of System.out output does not generate a problem, the new PRINTSTREAM object is created in the program generates a warning when compiling.

The method of the PrintWriter class with the PrintStream class is corresponding. There is a different reader to note that the functionality of the current automatic empty buffer is enabled (the autoflush in the constructor is set to TRUE), and only when the println () method is called, the buffer is automatically cleared, not When you encounter a newline in the same way as PrintStream.

To this end, we have introduced various types of filters I / O classes. Various corresponding filter classes suitable for byte streams and characters, their methods are also corresponding. Therefore, the readers who have not been introduced can reason close to their corresponding classes.

6 pipe I / O

Pipe I / O is specifically used for thread communication. Two classes are provided for byte stream Java, and the PiPedInputStream class is used to write byte data. Two pipe I / O stream objects can be connected, such a thread written data can be read by another thread. There are two classes for the character stream, namely PipedReader and PiPedWriter, respectively. We only detail the pipeline I / O class of word current flow.

6.1 PipedinputStream class

This class has two constructor. One free, after using it to establish input streams, it needs to be connected to a pipe output stream. Another pipe output stream (Pipedputstream) object is parameter, create an input stream connected to the output stream object.

All methods of the PipedInputStream class may throw IOEXCEPTION.

■ Public Void Connect (PiPedoutputStream SRC)

Connect the input stream to a pipe output stream.

■ Public synchronized int ■ public synchronized int tent (Byte B [], int offset, int ing

Read data.

■ Public void close ()

Close the stream.

6.2 PipedOutputStream Class

Compared with the PipedInputStream class, it has two constructor, one of which is parameter as a PipedInputStream object, and another. The member method also includes connect (), close (), and there are also two forms of Write () methods, which is not described here.

6.3 Example

The use of the specific demonstration of pipe I / O will be specifically demonstrated in one example (Example 5).

Example 5 PipeiodeMo.java

1: Import java.lang. *;

2: Import java.io.pipedinputstream;

3: Import java.io.pipedoutputstream;

4: Import java.io.ioException;

5:

6: Public class pipeiodemo {

7: public static void main (string args []) {

/ / The reader and Writer here are not the basic class of the character stream input and output, but it is customized below.

8: Reader Thread1 = New Reader ("1");

9: Writer thread2 = new Writer ("2");

// Joint pipeline

10: Try {

11: thread2.pipeout.connect (thread1.pipein);

12:} catch (ioexception ex) {

13: System.out.println ("IOException Occured When Connecting Two Stream");

14:}

// Start thread

15: thread1.start ();

16: thread2.start ();

// Loop, equal threads are ended after the process

17: DO {

18:} while (thread1.isalive () || thread2.isalive ());

19: System.out.println ("all over!");

20:}

twenty one:}

/ / Customize the reader class

22: Class Reader Extends thread {

23: Public PipedInputStream Pipein;

24: String threadname;

25: Public Reader (String Name) {

26: Super ();

27: threadname = name;

28: Pipein = new pipedinputstream ();

29:}

30: public void run () {

31: Try {

32: boolean over = false;

33: While (!!) {

34: INT ch = pipein.read ();

35: Try {

36: thread.sleep (200);

37:} catch (interruptedexception ex) {

38: System.out.println ("Sleep Is Interrupted!");

39:}

40: IF (CH == '.') Over = true;

41: Else System.Out.println ("Thread" Threadname "Read" (char) ch); 42:}

43:

44:} catch (ioException ex) {

45: System.out.println ("IOEXCEPTION OCCURED WHEN TRY TO Read Data");

46:}

47:}

48:}

// Customize the class

49: Class Writer Extends thread {

50: Public PipedoutputStream Pipeout;

51: String threadname;

// Written

52: String content = "Orange Apple";

53: Public Writer (String Name) {

54: Super ();

55: threadname = name;

56: pipeout = new pipedputstream ();

57:}

58: public void run () {

59: Try {

/ / Output the character string

60: for (int i = 0; i

61: Pipeout.write (Content.Charat (i));

62: Try {

63: thread.sleep (200);

64:} catch (interruptedexception ex) {

65: System.out.println ("Sleep is Interrupted!");

66:}

67: System.out.println ("Thread" ThreadName "Wrote" Content.Charat (i));

68:}

69: pipeout.write ('.');

70:} catch (ioexception ex) {

71: System.out.println ("IOException Occured When Try to Write Data";

72:}

73:}

74:}

The result of the program is as follows: (omitted)

This example is simple. Two threads, one is the reader, one is the writer, the content written by the reader. Both parties agree to end.

This example demonstrates the pipeline I / O general process, first to create a management I / O stream object. This job is made in the constructor of Reader and Writer class (line 28, 56). So when we created two thread1 and thread2 two threads, PIPEIN and PIPEOUT were created. Then we connect them, start two threads, and finally print "all over!" Means the end of the run.

It can be seen that the reading thread is actually not necessary to care about the other party. Their job is read or written, and each time the character output is displayed indicates that you have done. We added a large segment space in the output information of the PIPEIN, so the purpose is to make the output of the two threads can be easily distinguished. In addition, let two threads handle a character to sleep (Sleep) is not necessarily necessary, which is just the opportunity to increase the thread. If this paragraph last year, it may be performed several times without the phenomenon of thread1, thread2 alternate output information, and it is easy to misunderstand to be two threads must have a death to execute another. In addition, as the end of the end, it is not displayed.

This example is implemented one-way communication. In fact, the input stream objects and output flow objects are created for each thread, and two-way communication can be achieved separately. Readers are interested in trying. 7 other classes in java.io bag

7.1 SequenceInputStream class

This class's function is to merge multiple input streams. Its constructor has two, one with an enumeration object as a parameter, one with two inputStream objects as parameters. Methods There are two read () methods to read a character, read data into one of the by-unit arrays. Another is a close () method. Example 7.6 With it to achieve two parallel files. Among them, ByteArrayoutputStream is also used, and the result of two files is connected to the memory buffer first in the memory buffer. This example allows files to be destined to be one of two source files.

Example 6 Filecat.java

Import java.lang.system;

Import java.io. *;

Public class filecat {

Public static void main (string args []) {

SequenceinputStream seqin;

IF (args.length! = 3) {system.out.println ("USAGE: JAVA FileCAT Filesrc FileSrc FileDST");

Else {

Try {

FileInputStream F1 = New FileInputStream (Args [0]);

FileInputStream F2 = New FileInputStream (Args [1]);

Seqin = New SequenceInputStream (F1, F2);

ByteArrayoutputStream ByteArrayout = New byteArrayoutputStream ();

Boolean EOF = FALSE;

INT Bytecount = 0;

While (! EOF) {

INT C = seqin.read ();

IF (c == - 1) EOF = true;

Else {

// Write the data of the data to the byte array output stream

ByteArrayout.write ((char) c);

Bytecount;

}

}

FileOutputStream Outstream = New FileoutputStream (Args [2]);

// Write the data into the file

ByteArrayout.writto (Outstream);

System.out.println (Bytecount "bytes a read.");

Seqin.close ();

Outstream.close ();

ByteArrayout.Close ();

f1.close ();

f2.close ();

} catch (filenotfoundexception ex) {

System.out.println ("Cannot Open Source Files.please Check if They"

"exissrs and allows" ");

} catch (ioException ex) {

System.out.println ("IOEXCEPTION OCCURED!");

}

}

}

}

7.2 StreamTokenizer Class

This class is used to construct the lexical analyzer. By default, it can identify values, letters, and strings. Its constructor has only one to the input stream (the inputstream) object as a parameter. In this section, we give an example (Example 7.7) and introduce some methods of such classes that appear in the example.

Example 7.7 Tokeniodemo.java.

1: Import java.io.ioException; 2: Import java.lang.system;

3: Import Java.io.inputStreamReader;

4: Import java.io.streamTokenizer;

5: Import java.io.fileinputstream;

6:

7: public class tokeniodemo {

8: public static void main (string args []) throws oewception {

/ / Create input stream from the file

9: fileInputstream filein = new fileinputstream ("Hello.c");

// Create a word stream from byte stream

10: InputStreamReader Inreader = New InputStreamReader (Filein);

11: streamtokenizer tokenstream = New streamTokenizer (Inreader);

// Set the comment style

12: TokenStream.slashstarcomments (TRUE);

13: TokenStream.slashslashComments (TRUE);

// Identify the end of the line; if the parameters are false, end the line ends for blank characters

14: Tokenstream.eolissignificant (TRUE);

/ / Set the symbol of the quotation mark

15: tokenstream.quotechar ('");

// Set the character of the ASCII code 0-32 to blank characters

16: TokenStream.Whitespacechars (0,32);

17: Boolean EOF = FALSE;

18: DO {

19: int token = tokenstream.nextToken ();

20: Switch (token) {

// File end of the file

21: Case tokenStream.tt_eof:

22: System.out.print ("EOF");

23: EOF = True;

24: Break;

// Row end

25: Case tokenStream.tt_eol:

26: System.out.print ("eol");

27: Break;

//word

28: Case tokenStream.tt_word:

29: System.out.print ("Word" TokenStream.sval;

30: Break;

//digital

31: Case tokenStream.tt_number:

32: System.out.print ("Number" TokenStream.nVal);

33: BREAK;

34: DEFAULT:

35: System.out.print ("" (char) token);

36:}

37:} while (!!);

38: System.out.flush ();

39:}

40:}

Below is the operation result of this example:

E: /> Java tokeniodemo

# Word include eol eol word main () {Eol Word Print (",

Number 1234.0); EOL EOL} EOL EOF

E: />

Among them, the source code of the Hello.c program is as follows:

#include // to say "Hello World"

MAIN () {

Print ("Hello WORLD% D / N", 1234);

/ * IT is a test for tokeniodemo * /

}

In the example, we used such a method:

■ Public void Whitespacechars (int low, int hi)

Set a given range of characters to spaces (invisible) characters. Similar methods include WordChars () (set as word characters), ordinarychars () (set to other characters other than those with actual sense characters such as word characters, data characters).

■ Public void SlagStarcomments (Boolean Flag)

■ Public void SlashComments (Boolean Flag)

Flag is true, you can trained the corresponding annotation. Slashstar refers to a C style annotation (/*...*/). The latter refers to the C style annotation "//".

■ Public int nextToken ()

The next lexical analysis unit is obtained from the input stream.

■ Public Void Eolissingnificant (Boolean Flag)

If the parameter is true, the end of the line is recognized; otherwise, the end is closed as a blank character.

Some constants and variables are also used in the example. TT_EOF, TT_EOL, TT_NUMBER, TT_WORD indicate file ends, row ends, values, and words, respectively. Public String Sval is a string value; public Double NVAL refers to a double precision value. These constants, the use of variables has a clear demo in the example, and it will not be said here.

7.3 FileNameFilter interface

This interface is not common, only one way is provided:

■ Public Abstract Boolean Accept (File Dir, String Filename)

The function is to determine if a list of files contains the specified file.

7.4 SERIALIZABLE interface

The class that implements this interface can be "serialized", ie their objects can be converted to some form, which can be input and output, and the structure of the object is saved. That is, only this interface is implemented, the class object can be completely input and stored.

This interface does not contain any methods and variables, which only act as a tag. When programming, just in the class definition:

... Implements Serializable

This type of object can be "serial".

summary

In this chapter, we have more comprehensively introduced the classes and interfaces in the java.io package, and give an example. Readers learn through this chapter, you should master the Java input and output classes, and flexibly use the I / O means to self-compiled programs.

转载请注明原文地址:https://www.9cbs.com/read-57022.html

New Post(0)