IO for Java

Source: Internet
Author: User
Tags sin

All of the IO mechanisms in Java are input and output based on data streams that represent the flow sequences of character or byte data . So, what is data flow? A data stream is a collection of continuous data, like water in a water pipe, that supplies water at one end of a pipe , and a continuous flow at the other end of the pipe. A data writer can write data to a data flow pipeline in a paragraph or section, which forms a long stream of data sequentially. For a data reader, there is no segment of the data stream at the time of writing, it can read any length of data at a time, but it can only read the previous data before reading the data. The effect of reading is exactly the same, regardless of whether the data is written in multiple writes, or as a whole, once written.

"A stream is the source or endpoint of data stored in a disk or other peripheral device. ”

There are three ways to store data on your computer: external memory, memory, cache. The cache is inside the CPU. This summarizes reading data from external memory to memory and writes data from memory to external memory.

Flow is a very image of the concept, when the program needs to read the data , it will open a stream to the data source, can be a file, memory, network connection. When the program needs to write data , it opens a stream to the destination.

Java's IO model is very good, it uses the decorator mode, by the function of the stream, you can dynamically assemble the stream, in order to obtain the required functionality. For example, if you need a file input stream with buffering , you should use FileInputStream and Bufferedinputstream together.

Data flow: A sequence of sequences of bytes that have a starting point and an end point. Includes the input stream and the output stream.

Classification of data streams:

The data in a stream sequence can be either unprocessed raw binary data or a specific data that conforms to a certain format after a certain encoding has been processed. So there are two types of streams in Java:
1) Byte stream: The smallest data unit in the data stream is bytes
2) Character stream: the smallest data unit in the data stream is a character , the characters in Java are Unicode encoded , and one character occupies two bytes .

Standard input, output data stream:

1, standard output stream: System.out output data to a standard output device with a data type of printstream. Method: void print (); void println ()

2, standard input stream: System.in reads standard input device data, and its data type is InputStream. Method: int Read () returns the ASCII code, if return-1, indicates that no read to any byte read work ends.

int Read (byte[] b) reads in multiple bytes to buffer B, the return value is the number of bytes read in.

3, standard error stream: System.err output standard error. Its data type is PrintStream

Both the println or print methods implement multiple methods of outputting the base data type by overloading , including the output parameter type Boolean, char, int, long, float, and double. Also, overloads implement methods that output parameter types char[], string, and object. Where the print (object) and println (object) methods call the ToString method of the parameter Object at run time.

"InputStreamReader is a Bridge of bytes flowing into a character stream : It reads the bytes with the specified charset and decodes them into characters . ”
The construction method of the InputStreamReader InputStreamReader (InputStream in).
The in input stream (InputStream) is open and ready to provide input data. Typically, this stream corresponds to keyboard input or another input source specified by the host environment or user.
System.in is to accept bytes entered from the console
Can actually be regarded as
InputStream in = system.in;
InputStreamReader ISR = new InputStreamReader (in);

Java. Hierarchical architecture of IO:

The most important thing in the Java.io package is 5 classes and one interface. 5 classes refer to File outputstream inputstream Writer Reader an interface is Serializable

Java.io mainly consists of the following three levels:

1, streaming part---The main part of IO

2, the non-streaming part of the---mainly contains some of the auxiliary streaming parts of the class such as: File randomaccessfile filedescriptor

3, other classes---The file read section of the security-related classes, such as: Serializablepermission class, and the class of the filesystem associated with the local operating system, such as: FileSystem class and Win32filesystem class and Winntfiles Ystem class.

The main classes are as follows:

1,file (file characteristics and Management): used for file or directory description information, such as generating a new directory, modify the file name, delete files, determine the path of the file.

2,inputstream (binary format operation): abstract class, byte-based input operation, is the parent class of all input streams. Defines the common characteristics that all input streams have. cannot be instantiated

3,ouputstream (binary format operation): abstract class, byte-based output operation, is the parent class of all output streams. Defines the common characteristics that all output streams have. cannot be instantiated

The characters in Java are in the Unicode standard, one character is 16 bits, that is, one character is represented by two bytes. To do this, a stream that handles characters is introduced in Java.

4. Reader (file format operation): abstract class, character-based input operation.

5. Writer (file format operation): abstract class, character-based output operation.

6. Randomaccessfile (random file operation): It is feature-rich, can be accessed from anywhere in the file (input and output) operation .

Architecture diagram:

File class:

In the java.io package, the file class provides operations and management methods for describing files and directories.

Role: The file class is used primarily for naming files, querying file properties, and processing file directories.

public class File extends Object implements Serializable,comparable {}

The file class provides three different constructors with the flexibility to receive files and directory name information in different parameter forms.

1,file (String pathname)

Example: File F1=new file ("FileTest1.txt"); Create file Object F1,f1 refers to the file that is created under the current directory FileTest1.txt

2,file (String parent,string child);

Example: File F2=new file ("D:\\dir1", "FileTest2.txt");//Note: The D:\\dir1 directory must exist beforehand, otherwise the exception

3,file (File parent,string Child)

Example: File F4=new file ("\\dir3");
File F5=new file (F4, "FileTest5.txt");           If the \\DIR3 directory does not exist by using f4.mkdir () to create a file object corresponding to a disk files or directories, once created, you can obtain the properties of the file or directory by invoking its method. 1) public boolean exists () determines whether a file or directory exists
2) Public boolean isfile () determines whether the file or directory
3) Public boolean isdirectory () determines whether the file or directory
4) Public String GetName () returns the file name or directory name
5) Public String GetPath () returns the path to the file or directory.
6) public long length () Gets the size of the file
7) Public string[] List () returns all file names in the directory in a string array. Some methods of managing and manipulating files or directories are also defined in the file class, which are commonly used:
1) Public boolean renameto (File newFile); Renaming files
2) public void Delete (); deleting files
3) Public boolean mkdir (); Create a Directory java. IO Stream Class LibraryFour basic classes: InputStream, OutputStream and reader, writer class, they handle the byte stream and character stream respectively: 1) fileinputstream a file as a inputstream, to achieve the read operation of the file
2) Bytearrayinputstream: Use a buffer in memory as a InputStream
3) StringBufferInputStream: Use a String object as a InputStream
4) PipedInputStream: realized the concept of pipe, mainly used in the thread
5) Sequenceinputstream: Merge multiple inputstream into one InputStream 1) Bytearrayoutputstream: Put the information into a buffer in memory
2) FileOutputStream: Depositing information into a file
3) PipedOutputStream: realized the concept of pipe, mainly used in the thread
4) Sequenceoutputstream: Merge multiple outstream into one OutStream Java.nio package new I/O Class Library utilization Channels and BuffersAnd so on to improve the efficiency of I/O operations. 1. Specific classification of IO streams

One, by the type of I/O to the overall classification:

1. Memory1) Read/write data from/to memory array: CharArrayReader, Chararraywriter, Bytearrayinputstream, Bytearrayoutputstream
2) Read/write Data StringReader, StringWriter, StringBufferInputStream from/to memory string
2.Pipe PipeImplement pipeline input and output (interprocess communication): Pipedreader, PipedWriter, PipedInputStream, PipedOutputStream
3.File file Stream。 Read and write to the file: FileReader, FileWriter, FileInputStream, FileOutputStream
4. Objectserialization object input, Output: ObjectInputStream, ObjectOutputStream
5.DataConversion Data StreamRead and write by basic data type (processed data is the basic type of Java (such as Boolean, Byte, Integer, and floating-point numbers)): DataInputStream, DataOutputStream
6.PrintingIncludes convenient printing methods: PrintWriter, PrintStream
7.Buffering BufferingCache data when read in or written out to reduce I/O times: BufferedReader, BufferedWriter, Bufferedinputstream, Bufferedoutputstream
8.FilteringFilter FlowTo filter when the data is read or written: FilterReader, Filterwriter, FilterInputStream, Filteroutputstream
9.Concatenation Merge InputConnect multiple input streams into one input stream: Sequenceinputstream
10.Counting CountLine count when reading data: LineNumberReader, Linenumberinputstream
11.Peeking AheadPre-read by caching mechanism: Pushbackreader, Pushbackinputstream
12.Converting between Bytes and charactersConverts a byte stream to a stream of characters according to a certain encoding/decoding standard, or a reverse conversion (stream to Reader,writer conversion Class): InputStreamReader, OutputStreamWriter

two , categorized by data source (whereabouts):
1. File: FileInputStream, FileOutputStream, FileReader, FileWriter
2, Byte[]:bytearrayinputstream, Bytearrayoutputstream
3, char[]: CharArrayReader, Chararraywriter
4, String:stringbufferinputstream, StringReader, StringWriter
5. Network data stream: InputStream, OutputStream, Reader, Writer

BYTE Stream Inputstream/outputstream

1,inputstream Abstract class

Streams that inherit from InputStream are input data into the program , and the data is in bytes (8bit);

(1) public abstract int Read (): reads a byte of data, and the return value is the int type value of the high 0. if the return value =-1 no read to any byte read work ends.
(2) public int read (byte b[]): reads b.length bytes of data into a B array. The return value is the number of bytes read. The method is actually called by the next method to implement the
(3) public int read (byte b[], int off, int len): reads up to len bytes of data from the input stream and stores it in a B array with an offset of off.
(4) public int available (): Returns the number of bytes that can be read in the input stream. Note: If the input is blocked, the current thread will be suspended, and if the InputStream object calls this method, it will only return 0, and the method must be called by the subclass object that inherits the InputStream class.
(5) Public long skip (long N): ignores n bytes in the input stream, the return value is the number of bytes actually ignored, skips some bytes to read
(6) public int Close (): We must close our open stream after we have finished using it.

2.OutputStream Abstract class

1. public void Write (Byte b[]): Writes the bytes in parameter B to the output stream.
2. public void Write (byte b[], int off, int len): writes Len bytes from the offset off of parameter B to the output stream.
3. Public abstract void Write (int b): Converts an int to a byte type and writes low bytes to the output stream.
4. public void Flush (): Outputs all data in the data buffer and empties the buffer.
5. public void Close (): closes the output stream and frees the system resources associated with the stream.

Stream End judgment: The return value of the method read () is-1 o'clock; The return value of ReadLine () is null.

File input stream: FileInputStream class

FileInputStream can use the Read () method to read one byte at a time and return it as an int, or to read into a byte array when using the Read () method, the number of elements of a byte array, and how many bytes are enrolled in. In the process of completing or writing the entire file, such a byte array is usually used as a buffer because a byte array typically plays the intermediate role of the data.

Use Method (1)
File Fin=new file ("D:/abc.txt");
FileInputStream in=new FileInputStream (Fin);

Use Method (2)
FileInputStream in=new FileInputStream ("D:/abc.txt");

Examples of programs:
Display the contents of the Inputfromfile.java program on the Monitor

File output stream: FileOutputStream class

Mode 1:
File F=new file ("D:/myjava/write.txt");
FileOutputStream out= New FileOutputStream (f);
Mode 2:
FileOutputStream out=new FileOutputStream ("D:/myjava/write.txt");
Method 3: The constructor takes the FileDescriptor () object as its argument.
FileDescriptor () fd=new filedescriptor ();
FileOutputStream f2=new FileOutputStream (FD);
Method 4: The constructor takes the file name as its first parameter, and the Boolean value as the second argument.
FileOutputStream f=new FileOutputStream ("D:/abc.txt", true);
  Note: (1) When writing data in the file, overwrite the existing file if the file already exists, or (2) at the end of the read/write operation, call the Close method to close the stream.

Buffered input/output stream Bufferedinputstream/bufferedoutputstream

A buffer stream is a buffer allocated to each data stream, and a buffer is a temporary memory that stores data.

Bufferedinputstream: When writing data to the buffered stream, the data is written to the buffer, and when the buffer is full, the system sends the data to the output device at once.

Bufferedoutputstream: When the data is read from the buffer stream, the system reads the data from the buffer, and when the buffer is empty, the system will then read the data from the input device to the buffer.

1) Read the file into memory:

Connect Bufferedinputstream with FileInputStream

FileInputStream in=new FileInputStream ("file1.txt");

Bufferedinputstream bin=new Bufferedinputstream (in);

2) write the memory to the file:

Connect Bufferedoutputstream with FileOutputStream

Fileoutputstreamout=new FileOutputStream ("file1.txt");

Bufferedoutputstream bin=new Bufferedinputstream (out);

3) keyboard input stream read to memoryConnect the BufferedReader to the standard data stream InputStreamReader sin=new inputstreamreader (system.in); BufferedReader bin=new BufferedRead ER (sin);

Program Description:
Read the characters from the keyboard and write to the method of the BufferedReader class in the file: String readLine ()
Function: Reads a line of string, ending with a carriage return.
Methods of the BufferedWriter class: Bout.write (String S,offset,len)
Function: Writes the string s from offset to the Len length string from the buffer to somewhere.

Character Stream: Writer/reader

The characters in Java are in the Unicode standard, one character is 16 bits, that is, one character is represented by two bytes. To do this, a stream that handles characters is introduced in Java.

1. Reader abstract class

1) FileReader:Corresponds to FileInputStream
Mainly used to read character files, using the default character encoding, there are three kinds of constructors:
(1) The file name as a string: FileReader f=new filereader ("C:/temp.txt");
(2) The constructor takes the file object as its argument.
File F=new file ("C:/temp.txt");
FileReader f1=new FileReader (f);
(3) The constructor filedescriptor the object as a parameter
FileDescriptor () fd=new filedescriptor ()
FileReader f2=new FileReader (FD);
(1) using the specified character array as the parameter: CharArrayReader (char[])
(2) Character array as input stream: CharArrayReader (char[], int, int)
To read the string, the constructor is as follows: Public StringReader (string s);
2) CharArrayReader:Corresponds to Bytearrayinputstream
3) StringReader:Corresponds to StringBufferInputStream
4) InputStreamReader
Reads bytes from the input stream, converting them to characters: public InputStreamReader (InputStream);
5) FilterReader:Allow filtering of character streams
Protected FilterReader (Reader R);
6) Bufferreader:Accepts the reader object as a parameter and adds a character buffer to it, using the ReadLine () method to read a row.
Public Bufferreader (Reader R);

Main methods:

(1) public int read () throws IOException; Reads a character that returns a value of read character

(2) public int read (char cbuf[]) throws IOException; /* Reads a series of characters into the array cbuf[], the return value is the number of characters actually read */
(3) public abstract int Read (char cbuf[],int off,int len) throws IOException;
/* Reads Len characters, starts at the subscript off of the array cbuf[], and returns the number of characters actually read, which must be implemented by the subclass */

2. Writer Abstract class

1) FileWrite: corresponds to FileOutputStream
Writes character type data to a file, using the default character encoding and buffer size.
Public FileWrite (file f);
2) Chararraywrite: corresponds to the Bytearrayoutputstream and uses the character buffer as the output.
public Chararraywrite ();
3) Printwrite: Generate formatted output
Public PrintWriter (OutputStream OS);
4) Filterwriter: Used to write a stream of filter characters
Protected Filterwriter (Writer W);
5) PipedWriter: corresponds to PipedOutputStream

6) StringWriter: no corresponding byte-oriented stream

Main methods:

(1) public void write (int c) throws IOException;//writes the lower 16 bits of the integer value c to the output stream
(2) public void write (char cbuf[]) throws ioexception;//writes the character array cbuf[] to the output stream
(3) public abstract void Write (char cbuf[],int off,int len) throws IOException;//character array cbuf[] Len characters starting at the index off position in the output stream
(4) public void write (String str) throws IOException;//writes the characters in the string str to the output stream
(5) public void Write (string str,int off,int len) throws IOException;//writes the string str to the output stream from the Len character at the beginning of the index off
(6) Flush ()//brush empty output stream, and output all cached bytes.
(7) Close () closed stream public abstract void close () throws IOException

Reader and writer deal with the character stream, which involves the conversion of characters encoding when processing character stream.

Reader classes can convert characters in the input stream that use other encoding types to Unicode characters, and then allocate memory for them in memory
The writer class is able to convert in-memory Unicode characters to characters of other encoded types, and then write to the output stream.

Subclass of IOException Exception class:

1.public class Eofexception:
This type of exception is thrown when the end of the file is not properly reached or at the end of the input stream.
2.public class FileNotFoundException:
The exception that is thrown when the file is not found.
3.public class Interruptedioexception:
This type of exception is thrown when the I/O operation is interrupted.

Reference documents:

Http://blog.csdn.net/hguisu/article/details/7418161#comments

IO for Java

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.