Java entry note 7

xiaoxiao2021-03-06  37

1. Streams and I / OSTREAM are the communication path between the information source and the destination. The information source here can be file, memory, network, etc. Streams is mainly divided into input and Output Stream. 1.1 InputStream Class INPUTSTREAM is at the top level of the INPUT STREAM class, which mainly has the following methods: 1.1.1 Read method Read method to read data from the specified input stream, for the first time The start position of the stream begins to read, and the displacement is automatically implemented each at the last end portion from the last end area. The READ method has the following three forms: (1) int inTE buff [N]): When reading n bytes from the specified input stream into the buff, the method returns the number of characters read, if reading The actual number of bytes taken is less than N, which is generally because the end of the specified input stream has been read; (2) int: (): ie without parameters, this method reads data from the specified input stream each time one byte . The return value is also an int type, but it does not represent the number of bytes read, but the data of the data read from the stream, because the data itself is a Byte type, so it is generally forced to convert; if you read the stream The value returned at the end is -1; (3) int in (byte buff [n], int start, int LEN): Being data from the specified stream, starting from START, populating the LEN bytes into the buff, the return value is The actual number of fills, if the return value

Some input streams may have no capacity to return the number of bytes. If these input streams use the Avaiable method, the return value is 0.1.1.4 Close method For the open stream, Java can be automatically recycled, but Java automatically reclaims time, so the most I call the Close method to close the stream so that it is convenient for the next reset stream. 1.2 ByteArrayInputStreamByteArrayInputStream is inherited from an InputStream down, for extracting data from the byte array, an example for creating ByteArrayInputStream follows: byte [] buffer = new byte [1024]; // custom methods,; fillWithUsefulData (buffer) for filling data into buffer InputStream s = new ByteArrayInputStream (buffer); InputStream s1 = new ByteArrayInputStream (buffer, 100,300); wherein ByteArrayInputStream (buffer, 100,300) to create the buffer stream, starting from the first 100 bytes of buffer Take 300 bytes. Other methods of ByteArrayInputStream are similar to InputStream, which is no longer repeated. 1.3 FileInputStreamFileInputStream is also inherited from the InputStream and is used to extract from the specified file. Therefore, its method is similar to the method in InputStream, which is no longer introduced, only introducing special methods in FileInputStream: GetFd (), which is used to obtain file handles. The method is as follows: fileInputstream Afis = new fileinputstream ("AfileName"); fileDescriptor myfd = afis.getfd (); This file handle can be used when using an AFILENAME file (actually an instance of the file description class), such as To reopen the file, you can use FileInputStream Afis = New FileInputStream (Myfd). About file descriptions FileDescriptor, have the following description: (1) Property IN: Standard input; (2) Property OUT: Standard output; (3) Attribute err: Standard error output; there is another special method in FileInputStream Is: finalize (). 1.4 FilterInputStreamFilterInputStream is also inherited from the InputStream, but the FilterInputStream class basically cannot be used directly, usually uses the derived class of this class, such as BufferedInputStream, etc. This class is the most important feature in the definition can be nested: InputStream s = getAnInputStreamFromSomewhere (); FilterInputStream s1 = new FilterInputStream (s); FilterInputStream s2 = new FilterInputStream (s1); FilterInputStream s3 = new FilterInputStream (s2); therefore the All derived classes of the class have this feature.

1.5 BufferedInputStreamBufferedInputStream specified data source is a designated area of ​​memory, inherited from FilterInputStream down, this type of Stream mainly used to improve performance, which is generally designated InputStream when other definitions such as: InputStream s = new BufferedInputStream (new FileInputStream ( "foo ")); BufferedInputSream is the use of Mark and Reset methods, using the above nested methods, indirectly supports these methods. Because BufferedInputStream needs buffer, it needs to wait for the data before it arrived, so BufferedInputStream is best used in front of the stream, as above, of course, is not what is used in front. 1.6 DataInputStreamDataInputStream is also inherited from FilterInputStream, so it also has the characteristics of the parent class. DataInputStream is also an Implement DataInput interface, so DataInputStream specific methods, such as Readshort, ReadBoolean, ReadByte, ReadunSignedByte, Readshort, and so on. These methods are the extension of the Read method, and the use is similar, so it will not be described here.

The following is the implementation of Readint: public final int odint () THROWS IOEXCEPTION {INT CH1 = in.read (); int CH2 = in.read (); int CH4 = in.read () ; IF ((CH1 | CH2 | CH3 | CH4) <0) throw new eofexception (); return ((ch1 << 24) (CH2 << 16) (CH3 << 8) (CH4 << 0) } The following is the implementation of Readline: public final string readline () throws = linebuffer; if (buf == null) {buf = linebuffer = new char [128];} int room = buf.length ; Int offset = 0; int C; loop: while (true) {switch (c = in.read ()) {case -1: case '/ n': Break loop; case '/ r': int C2 = IN .read (); IF ((C2! = '/ n') && (C2! = -1)) {if (! (!) {this.in = new pushbackinputstream (in);} ((PushbackInputStream) ) in) .unread (c2);} Break loop; default: IF (--room <0) { BUF = New char [offset 128]; room = buf.length - offset - 1; System.ArrayCopy (Linebuffer, 0, BUF, 0, Offset); linebuffer = buf;} buf [offset ] = (char) C; Break;}} IF ((c == -1) && (offset == 0)) {Return Null;} Return String.copyValueof (BUF, 0, Offset);} In this example, if you read / r has to read a bit judgment whether it is / N, if not / N, have to put this character back to the input stream, so the function of the PushbackInputStream is used. If the read operation of DataInputStream has been to the end of Stream, it will throw an EOFEXCEPTION exception.

At the end of Stream, SkipBytes does not do any action; readline returns NULL; ReadUTF throws UtfdataFormatexception. 1.7 LINENUMBERINPUTSTREAM The same LINENUMBERINPUTSTREAM is inherited from FilterInputStream. This class can track the line number, set the line number, and the behaviors to recover. Generally do not directly use the class, using other indirect Stream nested it for use, such as: LineNumberInputStream aLNIS; aLNIS = new LineNumberInputStream (new FileInputStream ( "source")); DataInputStream s = new DataInputStream (aLNIS); String line WHILE ((line = s.readline ())! = Null) {... // process the line system.out.println ("DID LINE NUMBER:" alNis.getLineNumber ());} In this example Using DataInputStream reads line, use LINENUMBERINPUTSTREAM to monitor line. As can be seen from this sub, the flow of data in the nested stream penetrates through all streams, ie, the data in the stream flows synchronously. 1.8 PushbackInputStreampushbackInputStream is also inherited from FilterInputStream, which has a special method UnRead for discharging the read data. This method is used in an example readline, which corresponds to the read (), unread (byte []) and unread (byte [], int, int, int). 1.9 PipedInputStreamFilterInputStream's derived class has been introduced, and then introduce the derived class of InputStream. PipedInputStream typically uses PipedputStream together with two-way communication pipes between the threads. Therefore, it is not introduced to the use of PiPedInputStream. 1.10 StringBufferInputStreamString buffer = "Now is the time for all good men to come ..."; InputStream s = new StringBufferInputStream (buffer); 1.11 ByteArrayInputStreamByteArrayInputStream and StringBufferInputStream similar, except that it is based on ByteArry, based on the StringBufferInputStream String.

1.12 SequenceInputStreamSequenceInputStream for different InputStream strung together in chronological order, as the string together two InputStream: InputStream s1 = new FileInputStream ( "theFirstPart"); InputStream s2 = new FileInputStream ( "theRest"); InputStream s = new SequenceInputStream (S1, S2); The above can only achieve two input streams, to implement two or more input streams, you need to use the Vector class, as shown below: Vector v = new vector (3); ENUMERATION E; v.addelement (s1); v.addelement (s2); v.addelement (s2); e = v.elements (); inputstream s = new sequenceinputStream (e); 1.13 OutputStreamoutPutStream is located at the top of Output Stream class hierarchy, it It is an abstract class that specifies the basic functions of the Output Stream class. 1.13.1 WriteWrite method corresponds to the INPUTSTREAM's read method, which has three forms: (1) Write (byte []): Output data in the specified Byte array to the specified stream; (2) Write (byte [], int : INT: Start the data in the specified Byte array from the second parameter, output the length specified by the third parameter to the specified stream; (3) Wirte (int); output an int value to the specified stream; 1.13 .2 Flush and Close Some output streams are placed in the buffer during output, and these data can be truly written to the specified output stream using FLUSH. CLOSE is used to close the specified output stream. 1.14 BYTEARRAYOUTPUTSTREAMBYTEARRAYOUTPUTSTREAM points an output stream to a BYTE array, but this Byte array is built into byteArrayoutputStream inside, and does not require us to define. This class has two constructor: (1) ByteArrayoutputStream (): This constructor creates a BYTE array internally 32; (2) ByteArrayoutputStream (INT N): Creating a length N on the object .

ByteArrayoutputStream inherits from the OutputStream class, so it has methods such as Write, Flush and Close, and it also has the following special methods: (3) toString (): convert the Byte array inside the object into strings (String (BUF , 0, count): TOSTRING (INT N) transforms the BYTE array of the object to a string, the encoding mode is n; (5) TOSTRING (String n): convert the array of objects into characters Strings, coding mode is n; (6) TobyTearray (): Returns the BYTE array inside the object; (7) WRITETO (OutputStream): outputs the internal Byte array to the specified output stream; (8) reset (): Turn the object inside The length of the byte array is set to 0, {count = 0}; (9) Size (): Returns the Byte array length; 1.15 FileoutPutStreamFileoutPutStream corresponds to FileInputStream, which has the following constructor: (1) FileoutputStream (file) (2) FILEOUTPUTSTREAM (File File, Boolean Append): If Append is true, write files in an addition method, if it is not (default), write files in new ways; (3) FileoutPutStream (4) FileoutputStream String name) (5) FileOutPutStream (String Name, Boolean Append) Most of the standard methods, this is no longer introduced. Examples of use below: FileDescriptor fd = SomeFileStream.getfd (); OutputStream S = New FileOutputStream (FD); 1.16 FilterOutputStreamFilterOutputStream the corresponding FilterInputStream using similar methods inherited from FilterOutputStream .1.17 BufferedOutputStreamBufferedOutputStream, which corresponds with BufferedInputStream, a similar effect also, it is mainly to buffer the output stream, such as: OutputStream s = new Buffere DOUTPUTSTREAM ("FOO"))))))))); Because BufferedOutputStream is buffer data, it is necessary to use the FLUSH method to force the data in the buffer to truly write into the output stream. 1.18 DataOutputStreamDataOutputStream corresponds to DataInputStream, which implements the DataputPut interface while inheriting OutputStream, so it has a method specified in DataOutput, which is opposite to the method specified in DataInput.

It also has a Size method that returns the number of bytes written to the output stream. The following is an example of implementing replication functions: try {while (adi.readby ());} finally {adi.close (); ado.close ();} 1.19 PrintStreamPrintStream is from FilterOutputStream inherited from FilterOutputStream. Examples are as follows: PrintStream S = New PrintStream (New FileoutputStream ("Foo")); S.Println ("Here's The First Line of Text In The File Foo."); This example shows that you can write data to files using PrintStream, and This class provides the function of the output line, which makes up for the blank of DataOutputStream (in DataOutputStream does not have the function of the output line).

PrintStream constructor: (1) PrintStream (boolean autoFlush, OutputStream out) (2) PrintStream (OutputStream out) (3) PrintStream (OutputStream out, boolean autoFlush) (4) PrintStream (OutputStream out, boolean autoFlush, String encoding) 1.20 PipedOutputStreamPipedOutputStream PipedInputSteam cooperating with communication between the two threads, which are defined as follows: PipedInputStream sIn = PipedInputStream (); PipedOutputStream sOut = PipedOutputStream (sIn); Here is the example that the received data of the standard input and output to standard output: import java.io *; class ReadThread extends Thread implements Runnable {InputStream pi = null; OutputStream po = null; String process = null; ReadThread (String process, InputStream pi, OutputStream po) {this.pi = pi;. THIS.PO = PO; this.process = process;} public void run () {int ch; Byte [] buffer = new byte [12]; int Bytes_read; try {for (;;) {bytes_read = pi.read Buffer; // Read data IF from the specified stream (Bytes_read == -1) {return;} Po.Write (buffer, 0, bytes_read); // Written to the specified stream through the data thread.yield (); }} Catch (Exception e) {e.printStackTrace ();} finally {}}} public class MyPipe {public static void main (String [] args) {try {int ch; PipedInputStream writeIn = new PipedInputStream (); PipedOutputStream readOut = new PipedOutputStream (writeIn); FileOutputStream writeOut = new FileOutputStream ( "out"); ReadThread rt = new ReadThread ( "reader", System.in, readOut); ReadThread wt = new ReadThread ( "writer", writeIn, System.out Rt.Start (); wt.start ();

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

New Post(0)