1.What is IO
I/O operations in Java mainly refer to using Java for input and output operations. All Java I/O mechanisms are based on data streams for input and output. These data streams represent the flowing sequence of characters or byte data. Java's I/O streams provide standard methods for reading and writing data. Any object in Java that represents a data source will provide methods for reading and writing its data in a data stream.
Java.io is the main package for most data flow oriented input/output classes. In addition, Java also provides support for block transmission, and block IO is used in the core library java.nio.
The advantage of stream IO is that it is simple and easy to use, but the disadvantage is that it is less efficient. Block IO is very efficient, but programming is more complicated.
Java IO model:
Java's IO model design is very excellent. It uses the Decorator pattern to divide Streams by function. You can dynamically assemble these Streams to obtain the functions you need. For example, if you need a buffered file input stream, you should use a combination of FileInputStream and BufferedInputStream.
2. Basic concepts of data flow
Data flow is a collection of continuous data, just like the flow of water in a water pipe. Water is supplied bit by bit at one end of the water pipe, and what is seen at the other end of the water pipe is a continuous flow of water. The data writing program can write data into the data flow pipeline segment by segment. These data segments will form a long data stream in sequence. For data reading programs, the segmentation of the data stream during writing cannot be seen. Data of any length can be read each time, but only the previous data can be read first, and then the subsequent data can be read. data. Regardless of whether the data is written in multiple batches or written as a whole at once, the effect when reading is exactly the same.
"A stream is the source or destination of data stored on a disk or other peripheral device."
There are three ways to store data on a computer, one is external storage, one is memory, and the other is cache. For example, the hard disk, magnetic disk, USB flash drive, etc. on the computer are all external storage. There is a memory stick on the computer, and the cache is in the CPU. External storage has the largest storage capacity, followed by memory, and finally cache. However, the reading of data from external storage is the slowest, followed by memory, and cache is the fastest. Here is a summary of reading data from external memory to memory and writing data from memory to external memory. For the understanding of memory and external storage, we can simply understand it as a container, that is, external storage is a container, and memory is another container. So how to read the data in the external storage container into the memory container and how to save the data in the memory container to external storage?
In the Java class library, the IO part is very large because it covers a wide range of fields:
Standard input and output, file operations, data streams on the network, string streams, object streams, zip file streams, etc. In Java, the abstraction of input and output is called a stream, which is like a water pipe connecting two containers. Reading data from external memory into memory is called an input stream, and writing data from memory into external memory is called an output stream.
Stream is a very vivid concept. When the program needs to read data, it will open a stream to the data source. This data source can be a file, memory, or network connection. Similarly, when the program needs to write data, it will open a stream to the destination.
The basic concepts summarized are as follows:
An ordered sequence of bytes with a starting point and an ending point. Including input stream and output stream.
2) Input Stream:The program reads the data source from the input stream. Data sources include the outside world (keyboard, files, network...), which is the communication channel that reads the data source into the program
The purpose of using data streams is to make output and input independent of the device.
Input Stream does not care what device the data source comes from (keyboard, file, network)
The Output Stream does not care what device the data is destined for (keyboard, file, network)
3.Standard I/O
Java programs can exchange brief information with the outside world through command line parameters. At the same time, it also stipulates how to exchange information with standard input and output devices, such as keyboards and monitors. Through files, information in any data form can be exchanged with the outside world.
1. Command line parametersRunning results:
args[0] is <Java>
args[1] is <C>
args[2] is <VB>
The standard data stream that comes with the java system: java.lang.System:
Notice:
(1) The System class cannot create objects and can only use its three static members directly.
(2) Whenever the main method is executed, the above three objects are automatically generated.
1) Standard output stream System.out
System.out outputs data to the standard output device , and its data type is PrintStream. method:
2)Standard input stream System.in
System.in reads standard input device data (obtains data from standard input, usually the keyboard), and its data type is InputStream. method:
3)Standard error stream
System.err outputs standard error , and its data type is PrintStream. Please refer to the API for detailed instructions.
The standard output calls the println method through System.out to output parameters and wrap new lines, while the print method outputs parameters but does not wrap new lines. The println or print method implements multiple methods of outputting basic data types through overloading, including output parameter types of boolean, char, int, long, float, and double. At the same time, methods whose output parameter types are char[], String, and Object are also overloaded. Among them, the print(Object) and println(Object) methods will call the toString method of the parameter Object at runtime.
public class StandardInputOutput {
public static void main(String args[]) {
String s;
//Create a buffer reader to read data line by line from the keyboard
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(ir);
System.out.println("Unix system: ctrl-d or ctrl-c to exit"
+ "/nWindows system: ctrl-z exit");
try {
//Read one line of data and output it to the monitor as standard
s = in.readLine();
// If an I/O error occurs when the readLine() method is running, an IOException will be thrown.
while (s != null) {
System.out.println("Read: " + s);
s = in.readLine();
}
// Close the buffered reader
in.close();
} catch (IOException e) { // Catch any IO exceptions.
e.printStackTrace();
}
}
}
4.java.IO hierarchical architecture
The most important things in the entire Java.io package are 5 classes and an interface. The five classes refer to File, OutputStream, InputStream, Writer, and Reader; one interface refers to Serializable. Once you master these core IO operations, you will have a preliminary understanding of the IO system in Java.
Java I/O mainly includes the following levels, including three parts:
1. The main part of the streaming part IO;
2. The non-streaming part mainly includes some classes that assist the streaming part, such as: File class, RandomAccessFile class and FileDescriptor class;
3. Other classes - security-related classes in the file reading part, such as the SerializablePermission class, and file system classes related to the local operating system, such as the FileSystem class, Win32FileSystem class and WinNTFileSystem class.
The main classes are as follows:
1. File (File Characteristics and Management): Used for description information of files or directories, such as generating new directories, modifying file names, deleting files, determining the file path, etc.
2. InputStream (binary format operation): abstract class, byte-based input operation, and is the parent class of all input streams. Defines common characteristics that all input streams have.
3. OutputStream (binary format operation): abstract class. Byte-based output operations. Is the parent class of all output streams. Defines common characteristics that all output streams have.
Characters in Java adopt the Unicode standard. One character is 16 bits, that is, one character is represented by two bytes. To this end, streams for processing characters were 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 has rich functions and can perform access (input and output) operations from any location in the file .
The architecture of IO stream in Java is as follows:
5. Non-streaming file class--File class
}
Description: Methods of File class:
(1) exists() tests whether the specified file or directory exists on the disk
(2) mkdir() creates the directory specified by the file object (single-layer directory)
(3) createNewFile() creates the file specified by the file object
(4) list() returns all file name strings in the directory
6. Java.IO stream class library
The java.io package contains all the classes needed for streaming I/O. There are four basic classes in the java.io package: InputStream, OutputStream, Reader, and Writer classes, which handle byte streams and character streams respectively:
Basic data stream I/O
input/output
byte stream
character stream
input stream
Inputstream
Reader
output stream
OutputStream
Writer
Various other variations of streams in Java are derived from them:
JDK1.4 version began to introduce a new I/O class library, which is located in the java.nio package. The new I/O class library uses channels and buffers to improve the efficiency of I/O operations.
In the java.io package, java.io.InputStream represents the byte input stream, and java.io.OutputStream represents the byte output stream, which is at the top level of the java.io package. Both classes are abstract classes, which means that they cannot be instantiated and must be subclassed to achieve certain functions.
1. Specific classification of io flows1. Overall classification by I/O type:
1. Memory 1) Read and write data from/to the memory array: CharArrayReader, CharArrayWriter, ByteArrayInputStream, ByteArrayOutputStream
2) Read and write data from/to memory strings StringReader, StringWriter, StringBufferInputStream
2.Pipe pipeline implements pipeline input and output (inter-process communication): PipedReader, PipedWriter, PipedInputStream, PipedOutputStream
3.File file stream . Read and write files: FileReader, FileWriter, FileInputStream, FileOutputStream
4. ObjectSerialization object input and output : ObjectInputStream, ObjectOutputStream
5. The DataConversion data stream reads and writes according to basic data types (the data processed are Java’s basic types (such as Boolean, bytes, integers and floating point numbers)): DataInputStream, DataOutputStream
6.Printing includes convenient printing methods: PrintWriter, PrintStream
7. Buffering caches data when reading or writing out to reduce the number of I/O: BufferedReader, BufferedWriter, BufferedInputStream, BufferedOutputStream
8.Filtering filtering stream , filtering when data is read or written: FilterReader, FilterWriter, FilterInputStream, FilterOutputStream pass
9.Concatenation merges input and connects multiple input streams into one input stream: SequenceInputStream
10.Counting counts rows when reading data: LineNumberReader, LineNumberInputStream
11.Peeking Ahead performs pre-reading through the caching mechanism: PushbackReader, PushbackInputStream
12.Converting between Bytes and Characters converts the byte stream into a character stream according to certain encoding/decoding standards, or performs reverse conversion (Stream to Reader, Writer conversion class): InputStreamReader, OutputStreamWriter
2. Classification by data source (destination):
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
7. Byte stream InputStream/OutputStream
InputStream is a byte input stream. It is itself an abstract class and must rely on its subclasses to implement various functions. This abstract class is the super class of all classes that represent byte input streams. Streams inherited from InputStream input data into the program, and the data unit is bytes (8bit);
InputStream is a class used to input byte data, so the InputStream class provides three overloaded read methods. Common methods in the Inputstream class:
(1) public abstract int read(): Read a byte of data, and the return value is an int type value with the high bits filled with 0. If the return value = -1, it means that no bytes have been read and the reading work has ended.
(2) public int read(byte b[ ]): Read b.length bytes of data and put it into the b array. The return value is the number of bytes read. This method is actually implemented by calling the next method (3) public int read(byte b[ ], int off, int len): Read up to len bytes of data from the input stream and store it at an offset of off in the b array.
(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. If the InputStream object calls this method, it will only return 0. This method must be called by a subclass object that inherits the InputStream class to be useful.
(5) public long skip(long n): Ignore n bytes in the input stream, the return value is the number of bytes actually ignored, skip some bytes to read (6) public int close(): We are After use, the stream we opened must be closed.
Main subcategories:
1) FileInputStream uses a file as an InputStream to realize the reading operation of the file 2) ByteArrayInputStream: uses a buffer in the memory as an InputStream 3) StringBufferInputStream: uses a String object as an InputStream
4) PipedInputStream: implements the concept of pipe, mainly used in threads 5) SequenceInputStream: merges multiple InputStreams into one InputStream
Main subcategories:
1) ByteArrayOutputStream: Store information in a buffer in memory
2) FileOutputStream: Store information in a file
3) PipedOutputStream: implements the concept of pipe, mainly used in threads
4) SequenceOutputStream: Merge multiple OutStreams into one OutStream
Determination of the end of the stream: when the return value of the method read() is -1; when the return value of readLine() is null.
3. File input stream: FileInputStream classFileInputStream can use the read() method to read one byte at a time and return it as an int type, or use the read() method to read into a byte array. How many bytes are read according to the number of elements in the byte array. In the process of reading or writing the entire file, such a byte array is usually used as a buffer, because such a byte array usually plays an intermediate role in receiving data.
How to use(2)
FileInputStream in=newFileInputStream(“d: /abc.txt”);
Program example:
Display the contents of the InputFromFile.java program on the monitor
public class TestFile {
public static void main(String args[]) throws IOException {
try{
FileInputStream rf=new FileInputStream("InputFromFile.java");
int n=512; byte buffer[]=new byte[n];
while((rf.read(buffer,0,n)!=-1)&&(n>0)){
System.out.println(new String(buffer) );
}
System.out.println();
rf.close();
} catch(IOException IOe){
System.out.println(IOe.toString());
}
}
}
The FileOutputStream class is used to process data streams that use files as data output destinations; a string representing the file name, which can also be a File or FileDescriptor object.
There are two ways to create a file stream object:
Way 1:
File f=new File ("d:/myjava/write.txt ");
FileOutputStream out= new FileOutputStream (f);
Way 2:
FileOutputStream out=new FileOutputStream("d:/myjava/write.txt ");
Method 3: The constructor takes the FileDescriptor() object as its parameter.
FileDescriptor() fd=new FileDescriptor();
FileOutputStream f2=new FileOutputStream(fd);
Method 4: The constructor takes the file name as its first parameter and a Boolean value as its second parameter.
FileOutputStream f=new FileOutputStream("d:/abc.txt",true);
Note: (1) When writing data to a file, if the file already exists, the existing file will be overwritten; (2) When the read/write operation ends, the close method should be called to close the stream.
}
public class TestFile {
public static void main(String args[]) throws IOException {
try {
File inFile = new File("copy.java");
File outFile = new File("copy2.java");
FileInputStream finS = new FileInputStream(inFile);
FileOutputStream foutS = new FileOutputStream(outFile);
int c;
while ((c = finS.read()) != -1) {
foutS.write(c);
}
finS.close();
foutS.close();
} catch (IOException e) {
System.err.println("FileStreamsTest: " + e);
}
}
}
Computer access to external devices is time consuming. The higher the frequency of accessing external memory, the greater the probability that the CPU will be idle. In order to reduce the number of accesses to external memory, more data should be read and written in one access to the peripheral. To this end, in addition to the reading and writing mechanisms necessary for exchanging data between programs and flow nodes, a buffering mechanism should also be added. Buffered stream means that each data stream is allocated a buffer, and a buffer is a memory that temporarily stores data. This can reduce the number of accesses to the hard disk and improve transmission efficiency.
BufferedInputStream: When writing data to the buffered stream, the data is first written to the buffer. After the buffer is full, the system sends the data to the output device at once.
BufferedOutputStream: When reading data from the buffered stream, the system first reads the data from the buffer. When the buffer is empty, the system then reads the data from the input device to the buffer.
Connect BufferedInputStream to FileInputStream
FileInputStreamin=newFileInputStream( "file1.txt " );
BufferedInputStreambin=newBufferedInputStream(in);
2) Write memory to file:
Connect BufferedOutputStream to FileOutputStream
FileOutputStreamout=newFileOutputStream(“file1.txt”);
BufferedOutputStreambin=newBufferedInputStream(out);
public class ReadWriteToFile {
public static void main(String args[]) throws IOException {
InputStreamReader sin = new InputStreamReader(System.in);
BufferedReader bin = new BufferedReader(sin);
FileWriter out = new FileWriter("myfile.txt");
BufferedWriter bout = new BufferedWriter(out);
String s;
while ((s = bin.readLine()).length() > 0) {
bout.write(s, 0, s.length());
}
}
}
8. Character stream Writer/Reader
Characters in Java adopt the Unicode standard. One character is 16 bits, that is, one character is represented by two bytes. To this end, streams for processing characters were introduced in JAVA.
Abstract class for reading character streams. The only methods that subclasses must implement are read(char[], int, int) and close(). However, most subclasses will override some of the methods defined here to provide greater efficiency and/or additional functionality.
1) FileReader: Corresponding to FileInputStream, it is mainly used to read character files, using the default character encoding, and has three constructors:
(1) Use the file name as a string: FileReader f=new FileReader(“c:/temp.txt”);
(2) The constructor takes the File object as its parameter.
File f=new file(“c:/temp.txt”);
FileReader f1=new FileReader(f);
(3) The constructor takes the FileDescriptor object as a parameter
FileDescriptor() fd=new FileDescriptor()
FileReader f2=new FileReader(fd);
(1) Use the specified character array as parameter: CharArrayReader(char[])
(2) Use character array as input stream: CharArrayReader(char[], int, int)
To read a string, the constructor is as follows: public StringReader(String s);
2) CharArrayReader: corresponds to ByteArrayInputStream
3) StringReader: corresponds to StringBufferInputStream
4) InputStreamReader
Read bytes from the input stream and convert them into characters: Public inputstreamReader(inputstream is);
5) FilterReader: allows filtering character streams
protected filterReader(Reader r);
6) BufferReader: Accepts a Reader object as a parameter and adds a character buffer to it. Use the readline() method to read a line.
Public BufferReader(Reader r);
Main methods:
(1) publicintread()throwsIOException;//Read a character, the return value is the read character
(2) publicintread(charcbuf[])throwsIOException;/*Read a series of characters into the array cbuf[], and the return value is the number of characters actually read*/
(3) publicabstractintread(charcbuf[],intoff,intlen)throwsIOException;
/*Read len characters and store them starting from the subscript off of the array cbuf[]. The return value is the actual number of characters read. This method must be implemented by a subclass*/
Abstract class for writing to character streams. The only methods that subclasses must implement are write(char[], int, int), flush() and close(). However, most subclasses will override some of the methods defined here to provide greater efficiency and/or additional functionality. Its subcategories are as follows:
1) FileWrite: corresponds to FileOutputStream and writes character type data to a file, using the default character encoding and buffer size.
Public FileWrite(file f);
2) chararrayWrite: Corresponds to ByteArrayOutputStream, using the character buffer as output.
Public CharArrayWrite();
3) PrintWrite: Generate formatted output public PrintWriter(outputstream os);
4) filterWriter: used to write filter character stream protected FilterWriter(Writer w);
5) PipedWriter: corresponds to PipedOutputStream
6) StringWriter: There is no corresponding byte-oriented stream
Main methods:
(1) publicvoidwrite(intc)throwsIOException; //Write the lower 16 bits of the integer value c to the output stream (2) publicvoidwrite(charcbuf[])throwsIOException; //Write the character array cbuf[] to the output stream (3) publicabstractvoidwrite(charcbuf[],intoff,intlen) throwsIOException; //Write len characters starting from the index off in the character array cbuf[] to the output stream (4) publicvoidwrite(Stringstr)throwsIOException; //Write The characters in string str are written to the output stream (5) publicvoidwrite(Stringstr,intoff,intlen)throwsIOException; //Write len characters starting from index off in string str to the output stream (6) flush() / /Flush the output stream and output all buffered bytes.
(7)close() closes the stream publicabstractvoidclose()throwsIOException
3. The difference between InputStream and Reader, the difference between OutputStream and Writer
public static void main(String args[]) throws IOException {
System.out.println("Unicode character encoding is used in memory: ");
char c='good';
int lowBit=c&0xFF; int highBit=(c&0xFF00)>>8;
System.out.println(""+lowBit+" "+highBit);
String s="OK";
System.out.println("Local operating system default character encoding:");
readBuff(s.getBytes());
System.out.println("Using GBK character encoding:");
readBuff(s.getBytes("GBK"));
System.out.println("UTF-8 character encoding:");
readBuff(s.getBytes("UTF-8")); }
}
9. Subclasses of IOException exception class
1.public class EOFException:
This type of exception is thrown when the end of the file or the end of the input stream is reached abnormally.
2.public class FileNotFoundException:
Exception thrown when the file cannot be found.
3.public class InterruptedIOException:
This type of exception is thrown when an I/O operation is interrupted.