Java Advanced features IO stream

Source: Internet
Author: User

Buffered streams

Convert stream

Object Flow

Print Flow

Standard input/output stream

Random Access Stream

Array flow

About Flush (): All of the output streams of the processing stream, the outermost stream needs to be refreshed.

Javaio Flow

1 Understanding the File class

The object of the file class represents a file or a file directory

Absolute path: The full path to the file containing the drive letter

Relative path: The file path under the current path

The method in the file class involves the new, deleted, fetched path to file or file directory, and gets the size of the file. Does not involve writing or reading content to a file. Such a read or write function requires an IO stream to complete

Typically, the object of the file class is passed as an argument to the stream's constructor as the endpoint of the stream.

Operation of the file

CreateNewFile (): Create files on the hard disk corresponding to file

Delete (): Delete the file or file directory on the hard disk corresponding to the file object

Folder operations

MkDir ()/mkdirs (): Create a file directory. The difference between the methods of MkDir () and Mkdirs (): When the upper directory of the file directory to be created does not exist. This method puts back false, indicating that the creation was unsuccessful. Mkdirs () Creates a non-existent top-level file directory

List (): Enumerates the paths of all sub-files under the current file directory, string[]

Listfiles () lists all the sub-files under the current file directory. File[]

Other methods:

Exists (): Determines whether the current file or file directory exists on the hard disk

LastModified (): Time of last modification

Length (): Gets the size of the file contents, in bytes

Renameto (File newName): File1.renameto (file2): To return a value of true, you need to guarantee: File1 must exist on the hard disk; File2 must not exist on the hard disk

CanWrite ()

CanRead ()

Isfile ()

Isdirectory ()

GetName ()

GetPath ()

Getabsolutefile ()

GetAbsolutePath ()

GetParent ()

Classification of Java Streams

1 Follow flow direction: input stream vs output stream

2 per unit of processing data: byte stream vs character Stream

3 different roles by stream: node stream (file stream) vs processing stream

The node stream connects directly to the file, while the process flow acts as a mediator for the node flow and the program. 】

Framework structure of two Java streams

Abstract base class

InputStream OutputStream Reader Writer

Node stream (file stream)

FileInputStream FileOutputStream FileReader FileWriter

Buffer Stream (one of the processing flows to improve the efficiency of data transmission)

Bufferedinputstream Bufferedoutputsteam

BufferedReader BufferedWriter

Take the file input stream as an example to understand the details of the flow:

1 creates an object of the file class that maps a physical file. "The file class object is just a normal object and may not have a physical file"

File File = new file ("Hello.txt")

File.createnewfile ();

2 Create the corresponding input stream object, as the parameter of the input stream constructor as an object of the file class above (requires: the physical file read into must exist. ), otherwise the following exception is reported:

FileNotFoundException

FileInputStream fis = new FileInputStream (file);

3 implementation of the input stream

byte[] buffer = new BYTE[10];

int len;//is not buffer.length, but the number of bytes per read into the buffer byte array, len = fis.read (buffer)

while (len = fis.read (buffer))! =-1) {//read () method returns 1 if read to the end of the file

String str = new string (Buffer,0,len);

...//

}

4 closing of the stream

Fis.close ();

Note: The above is just the implementation of the FileInputStream stream, in the specific code, due to the existence of the exception, you also need to use the Try-catch-finally statement processing.

For the file output stream

1 if the output stream corresponding file does not exist, then in the process of output, the system will automatically create the corresponding file. This is not the same as the input stream.

2 if the output stream corresponding file exists, then the output process will overwrite the original file! Note: Not overwrite the contents of the file!

The string type is converted to a character array:

String str = "I love Java"; Byt e[] buffer = str.getbytes ();

Character array converted to string

String str = new string (buffer,0,buffer.length);

3 The best use of character streams for text files (TXT)

Use byte stream for non-text files (doc, JPG, mp3,mp4, etc.)

4, for the stream, must be manually closed.

What to look for in a buffered stream:

The buffer stream requires a manual flush, flush () method

InputStream and Reader are the base classes for all input streams.
InputStream (Typical implementation: FileInputStream) int Read ()
int read (byte[] b)
int read (byte[] b, int off, int len)

Reader (Typical implementation: FileReader)
int read ()
int read (char [] c)
The file IO resource opened in int read (char [] c, int off, int len) is not a resource in memory, the garbage collection mechanism cannot reclaim the resource, so the file IO resource should be explicitly closed.

OutputStream and Writer are very similar: void write (int b/int c); void Write (byte[] b/char[] cbuf); void Write (byte[] b/char[] buff, int off, int len); void Flush (); void Close (); The stream needs to be refreshed before it is closed because the character stream is directly in the action unit, so Writer can replace the character array with a string, that is, the string object as the parameter void write (string str); void Write (String str, int off, int len);

Buffered streams

To improve the speed of data read and write, the Java API provides a buffer-capable stream class that, when used with these stream classes, creates an internal buffer array that can be divided into: Bufferedinputstream and Bufferedoutputstream, depending on the data operating unit BufferedReader and BufferedWriter buffer stream to "socket" on the corresponding node stream, to read and write the data provides a buffer function, improve the efficiency of reading and writing, while adding some new methods for the output of the buffer stream, the written data will first in memory cache, Using flush () will cause the in-memory data to be written out immediately.

Convert stream

The conversion stream provides a conversion between the byte stream and the character stream the Java API provides two conversion streams: data in InputStreamReader and outputstreamwriter byte streams, and converting to character stream operations is more efficient.

InputStreamReader (InputStream is,stream CharSet)/

CharSet optional, if none, indicates the default local encoding

The charset represents a character set used to decode a file in the input stream. Used to decode bytes read in a byte stream into characters by the specified character set. Need and InputStream "socket". Construction method Public InputStreamReader (InputStream in) public Inputsreamreader (InputStream in,string charsetname) such as: Reader ISR = n EW InputStreamReader (system.in, "iso5334_1"); OutputStreamWriter the characters to be written out into the character stream are encoded into bytes by the specified character set, encoding process, need and outputstream "socket ”。 Construction method Public OutputStream Writer (OutputStream out)

Public Outputsream Writer (outputstreamout,stringcharsetname) At this time CharSet means to decode to the file.

Encoding: String –> byte array decoding: Byte array –> string all the files are stored in byte form, the operation read into is decoding, need to inputstreamreader, write the operation belongs to the code, need Outputsteamwriter class.

The encoding application of the conversion stream can store characters in the specified encoding format. Text data can be interpreted in the specified encoding format. Specifies that the action of the encoded table is done by the constructor

For use with standard input and output streams:

InputStreamReader reader = new InputStreamReader (system.in);

BufferedReader br = new BufferedReader (reader);

Br.readline ();//Gets a string from the keyboard, and then uses the type conversion to get its data, such as char and Int.

Standard input/output stream:

System.in and System.out respectively represent the system standard input and output devices the default input device is the keyboard, the output device is the type of the monitor system.in is InputStream The type of System.out is Printstream,printsteam is a subclass of OutputStream

The default device is changed by the Setin,setout method of the System class. public static void SetIn (InputStream in) public static void SetOut (PrintStream out) Scanner Scanner = new Scanner (system.in );

Print Flow

To convert the data format of the base data type to a string output print stream: PrintStream and PrintWriter provide a series of overloaded print and println methods for output from multiple data types The output of PrintStream and PrintWriter does not throw an exception PrintStream and PrintWriter has auto flush function System.out Returns an instance of PrintStream

PrintStream stream =

New PrintStream (New FileOutputStream ("Hello.txt"), true);

System.setout (PrintStream stream);

Data flow

To facilitate the manipulation of data in the Java language's basic data type, you can use data flow. There are two classes of data flow: (for reading and writing out data of basic data types) DataInputStream and DataOutputStream respectively "sockets" in InputStream and OutputStream Method in DataInputStream on node stream boolean Readboolean () byte readbyte () char ReadChar () float readfloat () Double readdouble () short Readshort () long readlong () int readInt () String readUTF () void readfully (byte[] b) The DataOutputStream method changes the read of the above method to the corresponding write. 1. Function: Save or read basic data type, String, byte[] byte array

2.DataInputStream and DataOutputStream

DataInputStream dis =

New DataInputStream (New FileInputStream (New File ("Data.dat"));

DataOutputStream dos =

New DataOutputStream (New FileOutputStream (New File ("Data.dat"));

dos.writexxx (xxx xxx); Dos.writeutf (String str);

Object Flow

ObjectInputStream and Ojbectoutputsteam: A processing stream used to store and read basic data type data or objects. The great thing about it is that you can write objects in Java to a data source, and you can restore objects from the data source. Serializable mechanism for Java objects:

Allows the conversion of in-memory Java objects into platform-independent binary streams, allowing this binary stream to persist on disk,

or transfer this binary stream to another network node over the network. When other programs get this binary stream, they can revert back to the original Java object

Serialization: A mechanism for saving basic type data or objects with the ObjectOutputStream class Deserialization: Mechanism for reading basic type data or objects with the ObjectInputStream class ObjectOutputStream and ObjectInputStream cannot serialize

Static and transient decorated member variables.

When we use the object stream to read into or write out, we need to ensure that the object is serialized, this is to ensure that the object can be written to the file, and can then read the object correctly back to the program. The vast majority of classes provided by Java are serialized.

If a class implements the Serializable interface, the class implementing the interface does not need to implement additional methods. However, the class requires a private static constant long type.

Private static final long serialid = 2233445555L;

Java Virtual Opportunity implements a method in the serializable interface that writes an object to a destination in a formatted text, and it is important to note that when you write to a file using an object stream, you not only guarantee that the object is serialized, but also that the object's member object must be serialized.

Using object flow to implement object cloning

Background: If two objects have the same reference, then they have the same entities and functions.

Sometimes we want a replica of the object, which is a copy of the original object entity, and the change of the replica entity is not synchronized to the original object entity. Object calls the Clone () method to get a copy of the object, called the cloned object of the original object.

It is important to note that if the original object has a reference member variable, the reference to the member variable of the cloned object is the same as the reference to the member variable of the original object, and because the reference is the same, the change of the member variable of the cloned object is synchronized to the member variable of the original object, and the program must override Clone () method, which undoubtedly increases the difficulty of programming.

Using object flow makes it easy to get a clone of a serialized object, we just need to write the object to the object output stream, and then call the object input stream to read back to the object, get a clone of the object, and there is no problem like this.

Random Access Stream

Randomaccessfile class support "Random Access" way, the program can jump directly to the file anywhere to read, write file support only access to the file part of the content can be added to the existing file after understanding:

Randomaccessfile, random access to a file behaves like a large byte array stored in the file system. There is a cursor or index that points to the suppressed array, called a file pointer.

int length (); Returns the length of the file

Randomaccessfile class object can freely move the record pointer: Long Getfilepointer (): Gets the current position of the file record pointer void Seek (long pos): Position the file record pointer to the POS location constructor public Randomaccessfile (file file, string mode) public Randomaccessfile (string name, string mode) creating an instance of Randomaccessfile class requires specifying a M The ODE parameter, which specifies the access mode of the Randomaccessfile: R: Open RW as read-only: Open for read and write to RWD: Open for Read and write; Update to synchronize file contents RWS: Open for Read and write, synchronize file contents and metadata updates public String ReadLine (); reads the next line of text, the file pointer is first moved down, and then read. The full Unicode character set is not supported.

Public final void Wirteutf (string str) writes a string to a file using UTF-8 's character encoding.

Random Access file stream: Randomaccessfile

    • 1. Can be either an input stream or an output stream

    • 2. As an output stream, if the output to the file does not exist, it will be created in the process of output, if the output to the file already exists, it is the content of the existing file is overwritten

    • 3. Achieve coverage of the data. (The concept of file pointers, starting from 0)

Array flow

The source and destination of the array stream is computer memory. byte array input stream Bytearrayinputstream, and byte array output stream Bytearrayoutputstream, each using the computer memory byte array as the source and destination of the stream, There are also classes of character arrays CharArrayReader and Chararraywriter.

Note: IO Exceptions do not occur in byte array streams.

Analyze the array flow as an example of a byte array:

Bytearrayinputstream (byte[] buf)

Bytearrayinputstream (byte[] buf,int offset,int len);

Specifies the source of the byte input stream in the constructor parameter

Methods to read from the stream:

public int read (), which reads a byte from the source, which returns a byte value.

public int read (byte[] buf) that reads bytes from the source into the parameter buf, which returns the number of bytes actually read out. If no bytes are read, return-1

Similarly: byte array output stream Bytearrayoutputstream (), parameter optional int type byte size, default to 32 bytes of buffer, can automatically expand.

public void Write (int b) writes out a byte to the memory buffer.

public void Write (byte[] buf,int off,int len), which writes out the specified number of bytes in the parameter buf to the memory buffer.

Public byte[] Tobytearray (), which returns all bytes written by the output stream to the buffer.

Object cloning can be perfectly implemented with object flow mates.

Java Advanced features IO stream

Related Article

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.