Java entry note 7

xiaoxiao2021-03-06  51

STREAMS and I / O

Street is the communication path between the information source and the destination. The source of the information can be file, memory, network, etc. Streams is mainly divided into input and Output Stream.

1.1 InputStream class

Class InputStream is at the top level of the INPUT Stream class, which mainly has the following methods:

1.1.1 read method

The READ method is used to read data from the specified input stream. The first time the first start position starts from the stream, and then the read is started from the last end portion, that is, the displacement is automatically implemented.

The READ method has the following three forms:

(1) Int read (BYTE BUFF [N]): When reading n bytes in the specified input stream into the buff, the method returns the actual number of bytes read, if the number of actual bytes read is less than N General, it is generally because of the end of the specified input stream;

(2) Int read (): That is, without parameters, this method reads data from the specified input stream each time a 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 Read (Byte Buff [N], Int Start, INT LEN): Read data from the specified stream, start from start, populate the LEN byte to buff, return the value as the actual number of fills, if return value

The following is a simple example of Read:

Import java.io. *;

Class testio1 {

Public static void main (string args []) {

InputStream S = NULL;

Try {

S = New FileInputStream ("IO.txt");

} catch (filenotfoundexception e) {

System.out.println ("File Not Find");

}

INT I;

Try {

i = s.read ();

While (i! = -1) {

System.out.println (CHAR) i);

i = s.read ();

}

} catch (ioexception e) {

System.out.println ("IO Error");

}}}

1.1.2 SKIP method

Skip methods are similar to LSEEK in the C language is used for positioning. SKIP method definition: long Skip (long n), the method moves n bytes in the current position in the specified stream, and the value of n can be a negative value for forward, the Skip method returns the value of the actual movement. For various reasons, if the value returned by the end or other cause is often less than n. For reading files, the cause of less than N is the greatest reason is to read the file end.

1.1.3 Available method

The Available method is used to calculate how many bytes currently in the specified stream, and if the specified stream is the file stream, then the file is returned. The value returned by Available is an int type.

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 open streams, Java can be automatically recycled, but Java automatically reclaims time, so it is best to call the Close method to close the stream, so that the next re-specified stream. 1.2 ByteArrayInputStream

ByteArrayInputStream is inherited from InputStream, used to extract data from the byte array, and the creation example of ByteArrayInputStream is as follows:

Byte [] buffer = new byte [1024];

FillWithuseFulData (Buffer); // Custom method for filling data in Buffer

InputStream S = New ByteArrayInputStream (BUFFER);

InputStream S1 = New ByTearRayinputStream (Buffer, 100,300);

Where ByteArrayInputStream (Buffer, 100, 300) is a stream created to buffer, starting 300 bytes from the 100th byte of Buffer.

Other methods of ByteArrayInputStream are similar to InputStream, which is no longer repeated.

1.3 fileInputstream

FileInputStream is also inherited from InputStream, 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 will use myFD this file handle (actually an instance of the file description class) when you use the AFileName file. If you want 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) Attribute OUT: Standard output;

(3) Attribute err: standard error output;

There is another special method in FileInputStream is: finalize ().

1.4 FilterInputStream

FilterInputStream 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. The biggest feature of this class is that it can be nested when defined:

InputStream S = getaninputstreamfromsomsomewhere ();

FilterInputStream S1 = New FilterInputStream (s);

FilterInputStream S2 = New FilterInputStream (S1);

FilterInputStream S3 = New FilterInputStream (S2);

So all of the derived classes of this class have this feature.

1.5 BufferedInputStream

BufferedInputStream specified data source is a memory area designated, 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 a Mark and Reset method that indirectly supports these methods using the nested methods described above.

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 DataInputStream

DataInputStream 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 an implementation of Readint:

Public final int ready () throws oException {

INT CH1 = in.read ();

INT CH2 = IN.READ ();

INT CH3 = 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 IOEXCEPTION {

Char buf [] = 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 (! (in instanceof pushbackinputstream) {

This.in = New PushbackInputStream (in);

}

(PushbackInputStream) .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 the read characters are read / R, it has to read a bit judgment whether it is / n, if not / n, it has to be placed 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, which can track line numbers, set line numbers, and markers to recovery to recovery. This class is generally not directly used, and the nested nesters of other streams are used indirectly, such as:

LINENUMBERINPUTSTREAM AlNis;

AlNis = New LinenumberinputStream (New FileInputStream ("Source"));

DataInputStream S = New DataInputStream (alNis);

String line;

WHILE ((line = s.readline ())! = null) {

....................

System.out.println ("DID LINE NUMBER:" AlNis.getLineNumber ());

}

In this example, use the DataInputStream read line to monitor lines using LINENUMBERINPUTSTREAM. 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 PushbackInputStream

PushbackInputStream 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 PipedinputStream

FilterInputStream's derived class has been introduced, and then introduce InputStream derived classes. 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 StringBufferInputStream

String buffer = "now is the time for all good men to come ...";

InputStream S = New StringBufferInputStream (BUFFER);

1.11 ByteArrayInputStream

ByteArrayInputStream is similar to StringBufferInputStream, but it is based on byterry, and StringBufferInputStream is based on String. 1.12 SEQUENCEINPUTSTREAM

SequenceInputStream is used to string from different inputStream, such as the two inputStream strings:

InputStream S1 = New FileInputStream ("THEFIRSTPART");

InputStream S2 = New FileInputStream ("Therest");

InputStream S = New SequenceInputStream (S1, S2);

Only two input streams can only be used, and more than two input streams are implemented, 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 OutputStream

OutputStream is located at the top level of the Output Stream class, which is an abstract class that specifies the basic functionality of the Output Stream class.

1.13.1 Write

The Write 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); outputs an int value to the specified stream;

1.13.2 Flush and Close

Some output streams are placed in the buffer when output, and the FLUSH can be used to truly write these data into the specified output stream. CLOSE is used to close the specified output stream.

1.14 ByteArrayoutputstream

ByteArrayOutputStream 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 of length 32 internally;

(2) BYTEARRAYOUTPUTSTREAM (INT N): Creating a BYTE array of length N in the object inside 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 (): Converts the Byte array inside the object into strings (string (buf, 0, count);

(4) TOSTRING (INT N): Transform the BYTE array of the object to the string, the encoding method is n;

(5) TOSTRING (String N): Transform the array of objects into strings, encoding mode is n; (6) TobyTearray (): Returns the BYTE array of object inside;

(7) WRITETO (OUTPUTSTREAM): Output the internal BYTE array to the specified output stream;

(8) RESET (): Set the length of the internal BYTE array of the object to 0, {count = 0};

(9) size (): Returns the length of the BYTE array;

1.15 FileOutputStream

FileOutputStream corresponds to FileInputStream, which has the following constructor:

(1) FileOutputStream (file)

(2) FileOutputStream (File File, Boolean Append): If the append is true, write the file in an add mode, if it is not (default), write files in a new manner;

(3) FileOutputStream (FileDescriptor)

(4) FileOutputStream (String Name)

(5) FileOutputStream (String Name, Boolean Append)

Most other methods are standard methods, which are no longer introduced. Examples of use below:

FileDescriptor fd = SomeFileStream.getfd ();

OutputStream S = New FileOutputStream (FD);

1.16 FilterOutputStream

FilterOutputStream corresponds to FilterInputStream, and the use method is also similar.

1.17 bufferedoutputstream

BufferedOutputStream inherited from FilterOutputStream, which corresponds to BufferedInputStream, and the role is similar, which is mainly buffered by output streams, such as:

OutputStream S = New BufferedOutputStream (New FileoutputStream ("foo"));

Since BufferedOutputStream is buffering 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 DataOutputStream

DataOutputStream corresponds to DataInputStream, in inheriting OutputStream, implements the DataOutput interface, 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 (true) ado.writebyte (adi.readbyte ());}

Finally {adi.close (); ado.close ();

1.19 PrintStream

PrintStream is inherited from FilterOutputStream. Use examples 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 the use of PrintStream to write data, and the class provides the function of the output line, making up for the blank of DataOutputStream (the function of DataOutputStream does not 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 PipedOutputStream

PiredOutputStream and PiPedInputSteam match each other communication between two threads, and their definitions are as follows:

PipedinputStream Sin = pipedinputstream ();

PipedoutputStream Sout = PipedoutputStream (sin);

The following is the use example, the example receives the data input data, and outputs it to the 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 tents_read;

Try {

For (;;) {

Bytes_read = pi.read (buffer); // Read data from the specified stream

IF (bytes_read == -1) {return;}

Po.write (buffer, 0, bytes_read); / / Writing data to the specified stream

Thread.yield ();

}

} catch (exception e) {E.PrintStackTrace ();

} finally {}

}

}

PUBLIC CLASSI

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 ();

} catch (exception e) {

E.PrintStackTrace ();

}}}

Description:

(1) Class readthread is very clever, it does not specify the specific type of input and output stream

(2) In the MyPIPE class, the New Readthread statement enables data from the standard input device, and the readout is PipedputputSteam, so it can be received by another thread;

(3) New ReadThread ("Writer", Writein, System.out, receives data from Writein, Writein is Readout is a pair of two-way pipes that receive data from Readout. Then output from standard devices.

1.21 randomaccessfile

1.22 streamtokenizer

1.23 ObjectOutputStream

ObjectOutputStream inherited from OutputStream and implemented two interfaces of ObjectOutput, ObjectStreamConstants. It is responsible for outputting the specified object to the specified output stream, which can output non-Static, non-Transient properties, and values, class definitions of the object to the specified output stream. This class has a very useful method:

WriteObject (Object obj);

This method outputs OBJ to the specified output stream, the following is an example of this class:

FileOutputStream F = New FileoutputStream ("TMP");

ObjectOput S = New ObjectOutputStream (f);

S.WriteObject ("Today");

S.WriteObject (New Date ());

S.flush ();

You can use the Transient modifier to specify that the value of some variables is not output to the specified output stream, such as:

Public Transient Int TransientValue = 4;

Such the value of TransientValue will not be output to the output stream.

1.24 ObjectInputStream

ObjectInputStream corresponds to ObjectOutputStream, which is read from the specified input stream of definition of the object's value and class to re-objective:

FileInputStream in = New FileInputStream ("TMP");

ObjectInputStream S = New ObjectInputStream (in);

String Today = (String) S.ReadObject ();

Date Date = (date) s.readObject ();

ObjectOutputStream and ObjectInputStream can make the object's persistence, that is, save the object serial to the media, re-recovering these objects when necessary.

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

New Post(0)