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 relationship of Java.io first, let us investigate the common output flow 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 │ ├SequenceInputStream │ ├StringBufferInputStream │ └ObjectInputStream ┌BufferedOutputStream │ ┌FilterOutputStream┼DataOutputStream Object┤ ├FileOutputStream └PrintStream ├OutputStream──┼ByteArrayOutputStream ├File ├PipedOutputStream ├FileDescriptor └ObjectOutputstream ├ObjDecstreamClass ├ObjdecstreamClass ├randomaccessFile └streamTokenizer Figure 1.1 Java.io package common class level map (excluding character flow class) Figure 1.1 contains many input and output classes (this does not include we are happy to be happy The character stream input and output class). In order to use them correctly, we must have a big root-based understanding of their functions and relationships. 1.1 byte streams are mentioned in Chapter 2 of the Characters 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 PipedOutputStream └StringWriter (none) 1.2 correspondence relationship between character stream type byte stream class Fig Further, the API version 1.1, version 1.0x some existing classes also tiny Modifications, this is mainly because there is a class of classes to bytes and characters. As methods and constructors marked as obsolete: Sting DataInputStream.readLine () InputStream Runtime.getLocalizedInputStream (InputStream) OutputStream Runtime.getLocalizedOutputStream (OutputStream) StreamTokenizer (InputStream) String (byte ascii [], int hibyte, int offset, int count) String (byte ascii [], int hibyte) void string.getbytes (int srte dst [], int dstbegin) Added the following constructor and method: streamTokenizer (Reader) Byte [] string.getbytes Void throwable.printStackTrace (PrintWriter) When programmers use old API programming, you can compile with Javac -DepRecation so that the compiler gives 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 Input Output Class Classification Java.IO Pack of each division, roughly, can be divided into the following categories: File 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 flow of "filtration" can be "filtered" by other filters, the commonality of the filter type is: (1) constructing with a variety of variations, and input filters Input flow, output filter output stream; (2) Non-obvious source / purpose restrictions; (3) The content "How much" content in the stream has not changed, and it is only possible to change 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 flow byte input stream InputStream and byte output stream OutputStream is two abstraction 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 square represented as follows: ■ public abstract int read () throws IOException ■ public int read (byte b []) throws IOException ■ public int read (byte b [], int offset, int length) throws IOException function from the input stream Read data. 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 input stream How much byte is readable. 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 releases resources. ■ Public Boolean Marksupperted () Returns the Boolean value indicating whether this stream can be tagged. ■ Public Synchronized Void Mark (Int Readlimit) is a tag for 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 Returns to the last time to make a tag. ■ Public long Skip (long n) throws orenception From the input streams a few bytes. 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 LENGTH) These three overload forms are used to write data to output of. Each of the particulars of each is unwillingly, the reader can control according to the foregoing read () method. ■ Public Void Flush () Clears 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 read () throws IOException ■ public int read (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 // stream is determined not to read ■ public boolean mark (int readAheadLimit) throws IOException ■ public void reset () throws IOException ■ Public Abstract Void Close () THROWS IOEXCEPTION3 File I / O In this section we will discuss the method and use of File, FileInputStream, FileoutputStream, FileInputStream, FileOutputFile class. 3.1 A file I / O instance allows us to 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 stream 7 : FileInputStream Instream = New FileInputStream ("text.src"); 8: fileoutputstream outstream = new fileoutputstream ("text.des"); // read and write output stream 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 (ooException ex) {20: system.out.println ("IOEXCEPTION OCCURED."); 21:} // 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 are randomly read and write.

"RW" represents readable writable 27: randomaccessfile rafile = new randomaccessfile ("text.des", "rw"); // Pointer is placed to file header 28: Rafile.seek (0); 29: Boolean EOF = FALSE; 30: System.out.Println ("The Content from Very Head:"); // Read File 31: While (! EOF) {32: INT C = Rafile.Read (); 33: IF (c == - 1 ) EOF = true; 34: else system.out.print (char) c); 35:} // 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 (ooException ex) {49: system.out.println ("RandomaccessFile Cause IOException! "); 50:} 51:} 52:} The results of the example 1 are as follows: () In order to fully display the role of the class associated with the 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 an object of the PrintStream class (there is no need to add Flush () without the contents of the buffer after PrintStream.

This feature of PrintStream, which can be removed (disable) when creating its object. This program is used in IOEXCEPTION and FILENOTFOUNDEXCEPTION. The latter is derived from the former, so if all TRY, CATCH in the program last year, while the main () method begins with Throws IOException, which can be. But this is not good to distinguish a variety of different exceptions, even if you can't find the text.src file we need, there will be no information display. This is undoubtedly a bad programming style. Therefore, we advocate each abnormality separately, so that the error can be mastered. 3.2 File Input Output Class library supports the following we will introduce the individuals used in Example 1. 1. There are three constructor of the File class File class. Create an instance according to the file name, file path and file name, file object (directory) and file name, respectively. That is: ■ Public file (String path) ■ Public file (String path) ■ Public file (file dir, string name) In addition to the examples used in the example, there are many methods, and only more common: ■ Public Boolean Exists () Determined the file ■ Public boolean canread () determines whether the file is readable ■ Public long length () Returns the file length ■ Public Boolean Mkdir () Create a directory ■ Public Boolean RenameTo (File Dest) file renamed, The last three methods may throw I / O abnormalities. It is 2.FileInputStream file input stream class constructor has three classes: ■ public FileInputStream (String fileName) throws FileNotFoundException ■ public FileInputStream (File file) throws FileNotFoundException ■ public FileInputStream (int fd) throws FileNotFoundException three constructors are the file name For the file object, the file descriptor creates a file input stream. The first one is used in the example. Methods: read (), skip (), available (), and close () rewrite the same name method of abstract class InputStream, which is as described above. Also: ■ Public Final INT getFd () returns the corresponding file descriptor. ■ ProtedTed Void Finalize () THROWS IOException Turns the input stream and collects 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 constructors: ■ public RandomAccessFile (String Filename, String mode) throws IOException ■ public RandomAccessFile (int FD) throws IOException ■ public RandomAccessFile (File file, String mode) throws IOException seen from the above, we can add a read-write file name Ways, file descriptors, file objects are readwritten, and their objects are created. 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. If readint () reads an integer writeouble () write a double precision floating point number, etc. 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, the word throttle refers to the use of ByteArrayInputStream and ByteArrayoutputStream class. 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 Sample example is the same as the above section, we still look at an example (Example 2) 2 BYTEARRAYIDEMO.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

Member Variable: protected byte buf [] Data Buffer Protected INT POS Buffer Current PROTECTED INT Count Buffer Number The number of items of this class is synchronized (SYNCHRONIZED). ■ Public synchronized int tent () reads a byte. ■ Public Synchronized Int Read (Byte B [], INT Offset, IntrLength) Reads multiple bytes, and 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 () Since the number of buffers internal bytes. ■ 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 variable: 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 [], int Offset, INT LENGTH) The array B is written to the buffer from the OFFSET from the OFFSET to Length. ■ Public Synchronized Void Writeto (OutputStream Out "Write the buffer content to another output stream OUT. ■ Public synchronized void reset () pointer is set to the buffer. 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 () returns buffer content as a byte array. ■ Public int size () Current buffer size. ■ Public string toString () ■ Public String Tostring (int hibyte) converts 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 It constructs a string as a parameter, prototype: ■ Public StringBufferInputStream (String S) The remaining member variables and methods are the same name with ByteArrayInputStream and the basic functions, this will not be described. 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 This section is much more, 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: The first example of the I / O of various data (Example 3) demonstrates the input and 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 IOException {// series filter 4: BufferedOutputStream bufOut = 5: new BufferedOutputStream (new FileOutputStream ( " Text.txt "); 6: DataOutputStream Data = New DataOutputStream (bufout); // Write various data 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 class 16: system.out.println (DataIn.Readboolean ()); 17: system.out.println (datain.readchar () ); 18: system.out.println (DataIN.Readint ()); 19: system.Out.println (DataIN.close (); 20: bufin.close (); 21: Datain.close (); 22: } 23:} The results of the example 3 are as follows: () The above example demonstrates DataInputStream, DataOutpurstream, BufferedInputStream, and BUFF EredoutputStream usage. 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 slower (output content first to buffer, then large block output) function, we add a filter to the file output to form: Data → Filter Object Bufout → File Output Slow, we use DataOut to write data, you can write all types of data to 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 exchange DataIn.ReadBoolean () DataIN.Readchar () read out is incorrect (note that the read is not character 't'), the format of various types of data stored is 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 The following we describe 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) a person an input stream constructs a filter input stream. Methods: Rewinding the same name method of InputStream, no new ways. The 2.FilterOutputStream class corresponds to the FilterOutputStream, providing a method of creating another output stream from an output stream. Constructor: ■ Public Filer OutputStream (OutputStream OUT) Creates a filter output stream by output stream. Methods: Rewind the same method of the OutputStream. 3. BufferedInputStream class starts from this class, we will 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: The method of rewriting the parent class. Skip (), Available (), Mark (), and reset () are synchronous (SYNCHONIZED). 4. The BufferedoutputStream class provides the "slow output" feature, and then 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 offset, int length) THROWS IOEXCEPTION ■ Public synchronized void flush () THROWS IOException The above method overrides the same name method for 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 methods in the Data I / O interface: ■ Public Abstract Void ReadFully (Byte Buffer []) reads all data to the buffer [] array. The system is in a blocking state. ■ Public Abstract Void ReadFully (Byte Buffer [], int offset, int futureTh is a place where the data is read from the OFFSET from OFFSET from OFFSET. ■ Public Abstract Int SkipBytes (int N) Skips the number of specified bytes. The return value is the number of bytes that actually skip. ■ Public Abstract String Readline () reads a line of data. In addition, there are three overload forms of the Write () method we have already familiar with. 6. After the DataInputStream class introduces two data I / O interfaces, the Data I / O stream is more simply. 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 ■ ■ Public final int ■ (Byte B [], INT Offset, INT LENGTH) Rewinds the same name method for FilterInputStream. DataInputStream has only one constructor. Like all filters, the parameters of this constructor are an object of InputStream. 7. We are very familiar with members of the class of DataOutputstream 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 Example 2: The line number and "Push-back" stream in the 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 oews oException {5: string s = "this is a multi-line string./n it is / job TO DEMO Filterio./N "; 6: char Array [] = new char [s.Length ()]; 7: for (int i = 0; i

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 supports the following detailed introduction to the new class in this case. 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. 1.PushbackReader class constructor two: ■ Public PushbackReader (Reader in, int size) Creating a PushbackReader object for buffer size is size. ■ Public PushbackReader (Reader IN) Creating a buffer size as a PushbackReader object of a character. Method: ■ Public int ■ Public int ■ reads data read (int offset, int lay ". ■ 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. The 2.LineNumberReader class constructor is two, similar to PushbackReader. The prototype of the method is listed below, where we are already familiar, there is no explanation. ■ Public int oException ■ Public int ■ The line number is set by PUBLIC IEXCEPTION ■ PUBLIC IEXCEPTION ■ ■ Public int getLineNumber () reads line number. ■ Public long Skip (long n) throws ioException ■ PUBLIC IEXCEPTION ■ Public Void Mark (int tentaheadlimit) THROWS IOEXCEPTION is tagged in the current location. Since then the ReadaheadLimit characters have become invalid. ■ Public void reset () THROWS IOException returns to the previous mark. 3. TheprintStream class and the PrintWriter class 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 a 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) Where AutoFlush is set to TRUE, each time the output encounters a newline, The content of the buffer is enforced all output, as in calling FLUSH (). But pay attention to that if there is no newline, there will be data "" in the buffer. Method (not explained): ■ Public void Write (INT B) ■ Public void Write (Byte B, INT Offset) ■ 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) 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 Pipeline 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 (PiredOutputStream SRC) Connects the input stream to a pipe output stream. ■ Public synchronized int ■ Public synchronized int tent (byte b [], int offset, intling) reads data. ■ Public void close () Close the stream. 6.2 The PipedOutputStream class is completely corresponding to the PiPedInputStream class, which 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 Program Example The following uses one example (Example 5) Specific demonstration of the use of pipe I / O.

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 the basic classes of the character stream input and output, but a custom 8: Reader Thread1 = New Reader ("1"); 9: Writer Thread2 = New Writer ("2"); // Liangji Tube 10: Try {11: thread2.pipeout.connect (thread1.pipein); 12:} catch (ooException 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 program stops 17: do {18:} While (Thread1.isalive () || thread2.isalive ()); 19: System.out.println ("All over!"); 20:} 21:} // Custom 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 Ove R = 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"); 46:} 47:} 48:} // Custom Writings Class 49: Class Writer Extends Thread {50: Public PiredOutputStream Pipeout; 51: String threadName; // To write content 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 {// String Content word output 60: for (int i = 0; I

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 data into file ByTeArrayout .writeto (outstream); System.Out.println (Bytecount "bytes aread."); seqin.close (); outstream.close ();

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 ioException {// 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 Note style 12: tokenStream.slashStarComments (true); 13: tokenStream.slashSlashComments (true); // identifying line terminator If the parameters are false, the line ends the line to end the line. The value 14: tokenstream.eolissignificant (TRUE); // Set the symbol of the quotation number representation 15: tokenstream.quotechar ('"); // Put the ASCII code 0-32 The character is set to the blank character 16: tokenstream.whitespacechars (0,32); 17: Boolean EOF = false; 18: do {19: int token = tokenstream.nextToken (); 20: switch (token) {// file end符 21: Case tokenStream.tt_eof: 22: System.out.print ("EOF"); 23: EOF = true; 24: Break; // Row end values ​​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; // Number 31: Case tokenStream.tt_number: 32: System.Number: 32: System.NUT.Print ("Number" TokenStream.nVal); 33: Break; 34: Default: 35: System.out .print ("" ("" (char) token; 36:} 37:} while (! EOF); ​​38: System.out.Flush (); 39:} 40:} The following is the operation result of this example: E: E: /> java tokeniodemo # word include eol eol word main () {eol word print (", Number 1234.0); eol eol} eol EOF E: />

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

New Post(0)