Chapter 1 Java I/O system

Source: Internet
Author: User
I. Basic usage Summary

1. The read method is a blocking method, that is, if no data in the stream object can be read, The read method will blockProgramContinue to run down until data can be read.

2. Because '\' is a special character in JavaCodeFor example, c: \ test \ Java \ hello. java, it must be written as "C: \ test \ Java \ hello. java "or" C:/test/Java/hello. java.

3. The file class contains most of the functional methods for file operations. The objects in this class can represent a specific file or folder.

4. Common byte input streams:

Input stream

Description

Bytearrayinputstream

Converts a byte array to an input stream.

Fileinputstream

Read data from a file

Stringbufferinputstream

Converts a string to an input stream. This class has been replaced by stringbufferreader.

Pipedinputstream

Connect to a pipedoutputstream

Sequenceinputstream

Converts several input streams into one input stream.

Objectinputstream

Object input stream

Filterinputstream

Decorator with the ability to expand other input streams

5. Common byte output streams:

Output stream

Description

Bytearrayoutputstream

Write Data to the byte array (memory buffer)

Fileoutputstream

Write data to a file

Pipedoutputstream

Output data to the pipeline, used together with pipedinputstream

Objectoutputstream

Object output stream

Filteroutputstream

Extends the functions of other output streams.

6. On the Java platform, you can use either of the following methods to obtain the character encoding type of the local platform:

A) system. getproperty ("file. encoding ");

B) charset cs = charset. defaultcharset (); Note: The charset class is located in the Java. NiO. charset package.

7. The reader class can convert characters of Other encoding types in the input stream to unicode characters, and allocate memory for These unicode characters in memory. The writer class can convert Unicode characters in memory to other encoding types before writing them to the output stream. By default, reader and writer are converted between the local platform and character encoding and Unicode character encoding ,:

If you want to input or output strings of a specific type, you can use the inputstreamreader class and outputstreamwriter class. In their constructor, you can specify the character encoding of the input stream or output stream. As shown below:

8. Common reader classes:

ReaderType

Description

Chararrayreader

Adapter to convert the character array to reader and read the characters from the character array.

Bufferedreader

Decorator that provides read buffer for other readers. In addition, its Readline () method can read a line of strings.

Linenumberreader

Decorator that provides a read buffer for other readers and tracks the symbols in the string input stream.

Stringreader

Adapter, converts a string to reader, and reads characters from the string

Pipedreader

Connect to a pipedwriter

Filterreader

Extends other reader functions.

Pushbackreader

Decorator, which can press a character to be read back to the buffer zone. It is usually used as a compiler scanner and is rarely used in programs.

Inputstreamreader

Adapter to convert inputstream to reader. You can specify the character encoding of the data source.

Filereader

Read characters from a file

9. Common writer classes:

WriterType

Description

Chararraywriter

Adapter, converts the character array to writer, and writes characters to the character array.

Bufferedwriter

Decorator that provides write buffer for other writer

Stringwriter

Adapter, converts stringbuffer to writer, and writes characters to stringbuffer

Pipedwriter

Connect to a pipedreader

Filterwriter

Extends other writer functions.

Printwriter

Decorator that outputs formatted data

Outputstreamwriter

Adapter to convert outputstream to writer. You can specify the character encoding of the data source.

Filewriter

Write characters to a file

Ii. Use of decorative streams

1. Commonly used decorative streams include datainputstream/dataoutputstream and bufferedreader/bufferedwriter. The decorative stream cannot be used independently. It must be a real stream or a decorative stream.

2. Only data written in the dataoutputstream stream format can be read using datainputstream. The following are examples of using dataoutputstream/datainputstream:

//Write data in a certain formatTest. MyFile.

// Mydata. Java

/**

* Simulate the data to be stored in the file

* This class stores four types of data

*/

Public ClassMydata {

BooleanB;

IntN;

String S;

ShortSh [];

PublicMydata (){}

PublicMydata (BooleanB,IntN, string s,ShortSh []) {

This. B = B;

This. N = N;

This. S = s;

This. SH = sh;

}

}

// Writefileusedatastream. Java

ImportJava. Io. dataoutputstream;

ImportJava. Io. fileoutputstream;

ImportJava. Io. ioexception;

/**

* Use dataoutputstream to write files in a certain format

*/

Public ClassWritefileusedatastream {

Public Static VoidMain (string [] ARGs ){

Short[] SH = {1, 3, 134,12 };

Mydata DATA =NewMydata (True, 100, "Java language", SH );

// Write a file

Writefile(Data );

}

/**

* Write the mydata object to the file in a certain format

*@ ParamData Object

*/

Public Static VoidWritefile (mydata data ){

Fileoutputstream Fos =Null;

Dataoutputstream dos =Null;

Try{

// Create a file stream

Fos =NewFileoutputstream ("test. My ");

// Create a data output stream and nesting the stream

DOS =NewDataoutputstream (FOS );

// Write data in sequence

Dos. writeboolean (data. B );

Dos. writeint (data. N );

Dos. writeutf (data. s );

// Write an array

IntLen = data. Sh. length;

Dos. writeint (LEN); // array Length

// Write each array element in sequence

For(IntI = 0; I <Len; ++ I)

Dos. writeshort (data. Sh [I]);

}Catch(Exception e ){

E. printstacktrace ();

}Finally{

Try{

Dos. Close ();

FOS. Close ();

}Catch(Ioexception e ){

//TodoAuto-generated Catch Block

E. printstacktrace ();

}

}

}

}

// Readfileusedatastream. Java

ImportJava. Io. datainputstream;

ImportJava. Io. fileinputstream;

/**

* Use datainputstream to read files in custom format

*/

Public ClassReadfileusedatastream {

Public Static VoidMain (string [] ARGs ){

Mydata DATA =Readfile();

System.Out. Println (data. B );

System.Out. Println (data. N );

System.Out. Println (data. s );

IntLen = data. Sh. length;

For(IntI = 0; I <Len; ++ I)

System.Out. Println (data. Sh [I]);

}

/**

* Read data from the file test. My and initialize the Data Object using the data read.

*@ ReturnRead object content

*/

Public StaticMydata readfile (){

Mydata DATA =NewMydata ();

Fileinputstream FCM =Null;

Datainputstream Dis =Null;

Try{

// Create a file stream

Fiis =NewFileinputstream ("test. My ");

// Create a data input stream and nested stream

Dis =NewDatainputstream (FCM );

// Read data in sequence and assign values to the Data Object

Data. B = dis. readboolean ();

Data. n = dis. readint ();

Data. S = dis. readutf ();

IntLen = dis. readint ();

Data. SH =New Short[Len];

For(IntI = 0; I <Len; ++ I)

Data. Sh [I] = dis. readshort ();

}Catch(Exception e ){

E. printstacktrace ();

}Finally{

Try{

Dis. Close ();

FCM. Close ();

}Catch(Exception e ){

E. printstacktrace ();

}

}

ReturnData;

}

}

3. There are two main bridge streams of the IO class: inputstreamreader and outputstreamwriter. The former converts inputstream and its subclass objects to objects in the reader system class, and converts byte input streams to Character Input streams; the latter converts the objects of outputstream and its subclass to the objects of the writer system class, and converts the byte input stream to the character input stream. Note that the bytes stream cannot be converted to a byte stream.

4. Io classes include a group of classes to improve read/write efficiency, including bufferedinputstream/bufferedoutputstream and bufferedreader/bufferedwriter. The following is an example. The function implemented by this Code is to echo user input and exit the program when the user inputs quit. :

ImportJava. Io. bufferedreader;

ImportJava. Io. inputstreamreader;

Public ClassReadconsolewithbuffer {

Public Static VoidMain (string [] ARGs ){

Bufferedreader BR =Null;

String S =Null;

Try{

// Use the nested stream to construct the buffer stream

BR =NewBufferedreader (NewInputstreamreader (system.In));

Do{

// Output prompt information

System.Out. Println ("Enter :");

// Read input by row

S = Br. Readline ();

// Output user input

System.Out. Println (s );

}While(! S. Equals ("quit "));

}Catch(Exception e ){

E. printstacktrace ();

}Finally{

Try{

BR. Close ();

}Catch(Exception e ){

E. printstacktrace ();

}

}

}

}

Iii. Standard I/O

1. the java. Lang. system class provides three static variables:

A) system. In: indicates the standard input stream of the inputstream type. The default data source is the keyboard.

B) system. Out: Specifies the standard output stream of the printstream type. The default data source is the console.

C) system. Err: Specifies the printstream type, indicating a standard error output stream. The default data source is the console.

2. The system class provides some static methods for redirecting a stream:

A) setin (inputstream in): redirects standard input streams.

B) setout (printstream out): redirects the standard output stream.

C) seterr (printstream out): redirects a standard error output stream.

Iv. Object serialization and deserialization

1. Only objects of classes that implement the java. Io. serializable interface can be serialized and deserialized. Some classes in the JDK class library (such as the string class, packaging class, and date class) all implement the serializable interface.

2. Object serialization involves the following steps:

A) create an object output stream, which can wrap an output stream of other types.

B) write an object using the writeobject () method of the object output stream.

3. perform the following steps to deserialize an object:

A) create an object input stream, which can wrap another type of input stream.

B) read the object through the readobject () method of the object input stream.

4. Ensure that the write object sequence for the output stream to the object is the same as that for the read object from the input stream of the object.

5. All attributes in the object will be serialized. serialization of sensitive information (such as user passwords) should be prohibited. The solution is to modify these attributes with transient so that they will not participate in the serialization and deserialization processes.

6. if you want to further control the serialization and deserialization methods, you can provide a readobject () and writeobject () methods in the class. When objectoutputstream/objectinputstream serializes and deserializes an object, if the object has a writeobject () or readobject () method, the method is executed. Otherwise, the serialization and deserialization are performed by default. In the writeobject () method, you can call the defaultwriteobject () method of objectoutputstream to execute the default serialization operation on the object output stream. In the readobject () method, you can call the defaultreadobject () method of objectinputstream, this causes the input stream of the object to perform the default deserialization operation. The following is the sample code:

ImportJava. Io. bytearrayinputstream;

ImportJava. Io. bytearrayoutputstream;

ImportJava. Io. ioexception;

ImportJava. Io. objectinputstream;

ImportJava. Io. objectoutputstream;

ImportJava. Io. serializable;

Public Class User ImplementsSerializable {

PrivateString name;

Private TransientString password;

PublicUser (string name, string password ){

This. Name = Name;

This. Password = password;

}

PublicString tostring (){

ReturnName + "" + password;

}

/**

* Encrypt the array and reverse each bit of each byte in the buff Array

* For example, the binary format of 13 is 00001101, And the inverse value is 11110010.

*/

Private Byte[] Change (Byte[] Buff ){

For(IntI = 0; I <buff. length; ++ I ){

IntB = 0;

For(IntJ = 0; j <8; ++ J ){

IntBit = (buff [I]> J & 1) = 0? 1: 0;

B + = (1 <j) * bit;

}

Buff [I] = (Byte) B;

}

ReturnBuff;

}

Private VoidWriteobject (objectoutputstream Stream)ThrowsIoexception {

Stream. defaultwriteobject (); // first serialize data in the default mode

Stream. writeobject (Change (password. getbytes ()));

}

Private VoidReadobject (objectinputstream Stream)ThrowsIoexception, classnotfoundexception {

Stream. defaultreadobject (); // deserialize the object by default.

Byte[] Buff = (Byte[]) Stream. readobject ();

Password =NewString (Change (buff ));

}

Public Static VoidMain (string [] ARGs)ThrowsException {

User user =New("Tom", "123456 ");

System.Out. Println ("before serializable:" + User );

Bytearrayoutputstream Buf =NewBytearrayoutputstream ();

// Serialize the user object to a byte Cache

Objectoutputstream o =NewObjectoutputstream (BUF );

O. writeobject (User );

// Deserialize the user object from the byte Cache

Objectinputstream in =NewObjectinputstream (NewBytearrayinputstream (BUF. tobytearray ()));

User = (User) in. readobject ();

System.Out. Println ("after serializable:" + User );

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.