I. Input/output stream
1. Stream: Different types of input, output source data streams: input or output data
All of the interfaces and classes of the Java data stream are defined in the Java.io package, so you should add them at the beginning of the program
Import java.io.*
2. Classification of streams:
(1) from the flow direction, the IO stream can be divided into the input stream and the output stream
Input stream: Data information flows from one place to the program
Output stream: Data information sent from a program to a destination
(2) From the Data Processing unit of the stream, the IO stream can be divided into byte stream and character stream.
BYTE stream: Binary data processed in bytes
Character streams: data streams processed as characters (Java uses the Unicode character set, which requires two bytes to hold one character)
(3) from the function of the stream, the IO stream can be divided into the node stream and the filter stream
Node Flow: The IO stream corresponding to the direct operation of the target device in the program
Filter stream (also known as wrapper flow): To invoke the corresponding node stream through an indirect IO stream, to be more flexible and convenient to read/write various types of data
Two, byte stream and character stream
There are two major inheritance systems in the 1.java.io package:
A class is a Stream that processes data in bytes, and they are named in ***stream
The other is reader and Writer, whose names are either *reader or *writer, that process data in a character unit.
Iii. file and file streams
Basic process of IO stream operation in 1.Java
Using the file class to locate a file--instantiate a Stream object by a byte stream or a subclass of a character stream
Read-write operation, close byte or character stream
The difference between a 2.Java byte stream and a character stream: A buffer is used when a character stream is manipulated, and a byte stream operation does not use a buffer
ImportJava.io.*;classFileStream { Public Static voidMain (string[] args) {Try{File InFile=NewFile ("File1.txt"); File OutFile=NewFile ("File2.txt"); FileReader FIS=NewFileReader (InFile); FileWriter Fos=NewFileWriter (OutFile); intC; while((c = Fis.read ())! = 1) {fos.write (c); } fis.close (); //fos.close ();Fos.flush ();//If this statement is not available, the File2.txt file is empty}Catch(FileNotFoundException e) {System.out.println ("FileStream:" +e); } Catch(IOException e) {System.out.println ("FileStream:" +e); } }}
Flush (); Statement force buffer output, no technology if using FileInputStream byte stream operation
The character stream is stored in the buffer before the buffer is full, unless you use flush () or close () to force the output
3. Under Windows System file name separator use "/" or escape character "\ \"
And the use of "/" in Linux
In order to keep the Java system very good portability, it is best to use file.separator when manipulating files
Example: File F = new file ("D:" + file.seperator + "test.txt");
The general use of "./" means the current directory, "... /"Indicates the parent directory of the current directory
4. Random file Read and write: Randomaccessfile class
Access mode values and meanings
Mode value |
Meaning |
"R" |
Open as read-only |
"RW" |
Open for Read and write, and if the file does not exist, try to create the file |
"RWS" |
Synchronous read/write, any write content is written directly to the physical file, including the file contents and file attributes |
"RWD" |
Synchronous read/write, any write content is written directly to the physical file, not including the file attributes |
RW mode, the update is only written to the file when the Randomaccessfile class object executes the Close method
The "RWS" and "RWD" modes are synchronous read/write so that the data can be updated in real time
General methods of Randomaccessfile class
Method name |
Meaning |
Public long Getfilepointer () throws IOException |
Returns the current file pointer position |
public void Seek (long pos) throws IOException |
Move the file pointer to the POS location |
public int skipbytes (int n) throws IOException |
The file pointer moves backwards n bytes, and n is negative when the pointer does not move |
public int read (byte[] b) throws IOException |
Reads a maximum of b.length bytes into the array b |
public void Write (byte[] b) throws IOException |
Writes B.length bytes from the specified array B to a file |
Public final byte ReadByte () throws IOException |
Read one byte |
Public final void WriteByte (int v) throws IOException |
Writes (Byte) v to the file |
Public final String ReadLine () throws IOException |
Read a row |
public void Close () throws IOException |
Close the stream |
Note: There is a ReadLine method in the class, but there is no WriteLine method
Iv. Filter Flow
1. Buffer Stream
To improve the read efficiency of IO streams, Java provides a buffer-capable stream class that creates an internal buffer when using these stream classes.
When a byte or character is read, the data that is read from the data source is populated to the buffer before returning
Improves the read efficiency of I/O streams by filling in the internal buffer with the written data and then writing it to the target data source once in the writing section or character
Buffered streams include:
BYTE stream: Bufferedinputstream Bufferedoutputstream
Character Stream: BufferedReader BufferedWriter
Note: The size of the buffer defaults to a size of 32 bytes, and the size of the general buffer is an integer multiple of the memory page or disk block, etc.
Data is actually sent to the output stream only when the buffer is full, but you can use the flush () method to artificially send data from a buffer that has not been filled
2. Data flow: DataInputStream and DataOutputStream
Function: Allows the program to read Java raw data in a machine-independent style, that is, does not care about how many bytes a value should be
Cases:
Importjava.io.IOException;ImportJava.io.DataInputStream;ImportJava.io.DataOutputStream;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream; Public classDatastreamdemo { Public Static voidMain (string[] args)throwsIOException {//Write the DataFileOutputStream fos =NewFileOutputStream ("Data.txt"); DataOutputStream dos=NewDataOutputStream (FOS); Dos.writeboolean (true); Dos.writebyte ((byte) 123); Dos.writechar (J); Dos.writedouble (3.1415926); Dos.writefloat (2.7182f); Dos.writeint (1234567); Dos.writelong (998877665544332211L); Dos.writeshort (( Short) 11223); Dos.close (); //Read the dataFileInputStream FIS =NewFileInputStream ("Data.txt"); DataInputStream Dis=NewDataInputStream (FIS); System.out.println (Dis.readboolean ()); System.out.println (Dis.readbyte ()); System.out.println (Dis.readchar ()); System.out.println (Dis.readdouble ()); System.out.println (Dis.readfloat ()); System.out.println (Dis.readint ()); System.out.println (Dis.readlong ()); System.out.println (Dis.readshort ()); Dis.close (); }}
3. Print Flow: A class that makes output information more convenient, mainly including PrintStream and PrintWriter
Include output method print println printf
V. Standard FLOW
1. The system class in Language Pack Java.lang manages standard IO streams and error streams. System is the final class, and the following three static variable member variables are defined in the System class
public static final InputStream in: standard input, usually keyboard
public static final PrintStream out: standard output, typically display
public static final PrintStream ERR: Error message output, usually a monitor
Cases:
Public classSystemdemo { Public Static voidMain (string[] args) {Try { byteBarray[] =New byte[20]; String str; System.out.print ("Input:"); System.in.read (Barray); STR=NewString (Barray, 0); System.out.print ("Output:"); System.out.println (Str.trim ()); } Catch(IOException IoE) {System.err.println (ioe.tostirng ()); } }}
Vi. Object Flow
1. Serialization of objects: The method of turning an object into a binary data stream enables the transfer and storage of objects
Only classes that implement the Java.io.Serializable interface can be serialized
There is no method in the Java.io.Serializable interface, a class declaration implementation java.io.Serializable only indicates that the class is joined to the object Serialization protocol
2. Object Flow
Classes ObjectOutputStream and ObjectInputStream inherit the interfaces ObjectOutput and ObjectInput
Extend the data flow capability to read/write objects by: ReadObject (); and WriteObject ();
Note: As a general rule, all properties in the class object of a class are serialized as long as they implement the serializable interface.
For some sensitive information, simply use the transient modifier on the non-serialized attribute
Seven, Scanner class
The 1.Scanner class is in the Java.util package and needs to be imported with import
Common methods of Scanner class
Method name |
Meaning |
Public Scanner (InputStream source) |
Receive content from the specified byte input stream |
Public Scanner (File source) throws FileNotFoundException |
Receive content from a file |
public boolean hasnextint () |
Determines whether the input is an integer |
public boolean hasnextdouble () |
Determine if the input is a decimal |
Public String Next () |
Receive data |
public int Nextint () |
Receive integers |
public float nextdouble () |
Receive decimals |
Public Scanner Usedelimiter (String pattern) |
Set delimiter |
Cases:
New Scanner (system.in); while (Reader.hasnextdouble ()) { double x = reader.nextdouble ();}
Eight, the choice of flow
1. Steps:
(1) Select the appropriate node stream: Select According to the type of data source of the link
Read-write files should use a file stream, and read-write byte arrays should use byte array streams
(2) Select the appropriate direction of flow: read: Input stream/write: output stream
(3) Select a byte stream or character stream: All files are transmitted in bytes (including images, etc.)
Characters are only formed in memory, so the byte stream is used more broadly
(4) Packaging flow: You can select multiple, for example:
If you need to read/write formatted data, select Datainputstream/dataoutputstream
If you need to improve the efficiency of read/write, select Bufferedreader/bufferedwriter
Java Learning Note -7.java IO stream