Note: Lecture 4 exception handling and I / O flow in Java

[thinking before class] 1. What are exceptions? What are the two exception handling mechanisms in Java? 2. What are the base classes of byte stream and character stream? 3. What is object serialization? What is the role of object serialization?

Difficulties: 1. How to use the two exception handling mechanisms in Java, the difference and relationship between discarding exceptions and declaring discarding exceptions. 2. 2. When processing character stream, the parameter of its construction method is a byte stream. 3. The concept of object serialization.

4.1 what are exceptions

4.1.2 exception handling mechanism

Throw exception: if an exception event occurs during the execution of a java program, an exception object will be generated. The generated exception object will be passed to the Java runtime system. The generation and submission process of this exception is called throw exception.

Two mechanisms to deal with exceptions: ◇ capture exceptions: when the Java runtime system gets an exception object, it will trace back layer by layer along the method call stack to find the code to deal with this exception. After finding a method that can handle this type of exception, the runtime system hands over the current exception object to this method for processing. This process is called catch exception. This is a positive exception handling mechanism. If the Java runtime system cannot find a method to catch exceptions, the runtime system will terminate and the corresponding Java program will exit. ◇ declare to discard exceptions: if a method does not know how to handle the exceptions, it can declare to throw exceptions when declaring the method. This is a negative exception handling mechanism.

4.1.3 hierarchy of exception classes in JDK, exception classes are defined in each package, and all exception classes inherit from throwable class directly or indirectly. Figure 4-1 shows the inheritance relationship of exception classes in JDK.

Exception classes in Java can be divided into two categories: error, dynamic link failure, virtual machine error, etc. generally, Java programs should not capture such exceptions or abandon them. Exception 1) runtime exception: classes inherited from runtimeException belong to runtime exceptions, For example, arithmetic exceptions (except zero error), array subscript out of bounds exceptions, etc. because the location of these exceptions is unknown, the java compiler allows programmers not to deal with them in the program. 2) non runtime exceptions: except for runtime exceptions, other exception classes inherited from exception are non runtime exceptions, such as FileNotFoundException (no exception found in the file). The java compiler requires that this exception must be handled in the program, catch the exception or declare to discard the exception.

4.2 exception handling 4.2.1 exception capture exception is realized through the try catch finally statement:

4.2.2 disclaimer of exceptions

4.3 use of custom exception classes

The custom exception class must be a direct or indirect subclass of throwable. Note: exceptions declared by a method exist as part of the method's interaction with the outside world. Therefore, method callers must understand these exceptions and determine how to handle them correctly.

4.4 I / O flow overview input / output processing is a very important part of program design, such as reading data from the keyboard, reading data from files or writing data to files, etc. Java abstracts these different types of input and output sources into streams, which are represented by unified interfaces, so as to make the program simple and clear. JDK provides the package java.io, which includes a series of classes to implement input / output processing. Next, we will briefly introduce the contents of the java.io package.

4.4.1 hierarchy of I / O stream 1. Byte stream: a series of classes derived from InputStream and OutputStream. Such streams take bytes as the basic processing unit.   ◇ InputStream、OutputStream   ◇ FileInputStream、FileOutputStream   ◇ PipedInputStream、PipedOutputStream   ◇ ByteArrayInputStream、ByteArrayOutputStream   ◇ FilterInputStream、FilterOutputStream   ◇ DataInputStream、DataOutputStream   ◇ BufferedInputStream、 Bufferedoutputstream 2. Character stream: a series of classes derived from reader and writer. This kind of stream takes the characters represented by 16 bit Unicode code as the basic processing unit.   ◇ Reader、Writer   ◇ InputStreamReader、OutputStreamWriter   ◇ FileReader、FileWriter   ◇ CharArrayReader、CharArrayWriter   ◇ PipedReader、PipedWriter   ◇ FilterReader、FilterWriter   ◇ BufferedReader、BufferedWriter   ◇ StringReader、 Stringwriter 3. Object stream ◇ objectinputstream, objectoutputstream 4. Other ◇ file processing: file, RandomAccessFile; ◇ interfaces: datainput, dataoutput, objectinput, objectoutput; 4.4.2 InputStream and OutputStream

1. InputStream ◇ read data from stream: int read()// Read a byte, and the return value is the read byte int read (byte B [])// Read multiple bytes and place them in byte array B. usually / / the number of bytes read is the length of B, and the return value is the actual number of bytes / / read int read (byte B [], int off, int len)// Read len bytes and place / / them in the off start byte / / array B. the return value is the actual number of bytes read. Int available(); / / the return value is the number of bytes in the stream that have not been read. Long skip (long n)// The read pointer skips n bytes and does not read. The return value is the actual number of bytes. / / skips ◇ close the stream: close()// After the stream operation is completed, it must be closed ◇ use the flag in the input stream: void mark (int readlimit)// Record the current position of the read pointer. Readlimit / / indicates that the read pointer reads readlimit bytes. / / the marked pointer position becomes invalid void reset(); / / re point the read pointer to the position recorded by the mark method, Boolean marksupported(); / / whether the current stream supports the recording function of read pointer 2. OutputStream ◇ output data: void write (int b); / / write a byte B void write (byte B []) to the stream// Write a byte array B void write (byte B [], int len) to the stream// Start from / / subscript off in byte array B and write bytes of length len into the stream ◇ flush() / / empty the output stream and output all cached bytes. Since some streams support caching function, this method will force all contents in the cache to be output to the stream. ◇ close flow: close(); / / the stream must be closed after the operation

4.4.3 exceptions in I / O

I / O exceptions may occur during I / O operations, which are non runtime exceptions and should be handled in the program. Such as FileNotFoundException, eofexception, IOException.

4.5 document processing

In I / O processing, the most common is the operation of files, Java The classes related to file processing in the IO package include: file, FileInputStream, fileoutputstream, ramdomaccessfile and filedescriptor; Interface: filenamefilter. 4.5.1 file description class file provides a machine independent way to describe the attributes of a file object. Next, we introduce the various methods provided in the file class.

4.5.2 file sequential processing classes FileInputStream and fileoutputstream are used for file I / O processing. The methods provided by them can open files on the local host and read / write sequentially. For example, the following statement segment reads the contents of the file named text in sequence and displays them on the console until the end of the file.

FileInputStream fis; Try {FIS = new FileInputStream ("text"); system. Out. Print ("content of text is:"); int b; while ((b = FIS. Read())! = - 1) / / read the contents of the file text in sequence and assign them to the integer variable B until the end of the file {system. Out. Print ((char) b);}} catch (FileNotFoundException E) {system. Out. Println (E);} catch (IOException E) {system. Out. Println (E);} 4.5.3 random access files for InputStream and OutputStream, Their instances are sequential access streams, that is, they can only read / write files sequentially. Random access to files allows random reading / writing of file contents. In Java, the class RandomAccessFile provides methods to access files randomly. The declaration of class RandomAccessFile is: public class RandomAccessFile extends object implements datainput, dataoutput

The methods defined in the interface datainput mainly include reading basic type data from the stream, reading a row of data, or reading the number of bytes of a specified length. Such as readboolean(), readint(), readline(), readfull(). The methods defined in the interface dataoutput are mainly to write basic type data to the stream or write a byte array of a certain length. Such as writechar(), writedouble(), write(), etc. The methods in the RandomAccessFile class are described in detail below. ◇ construction method: RandomAccessFile (string name, string mode)// Name is the file name, and mode / / is the opening mode. For example, "R" means read-only, "RW" means read-write, "RandomAccessFile (file, string mode); / / file is a file object ◇ operation of file pointer long getfilepointer(); / / used to get the current file pointer void seek (long POS); / / used to move the file pointer to the specified position int skipbytes (int n); / / move the file pointer forward by the specified n bytes

4.6 filtered flow

Filtering streams can process data while reading / writing data. It provides a synchronization mechanism so that only one thread can access an I / O stream at a time, so as to prevent unexpected results caused by multiple threads operating on an I / O stream at the same time. The classes filterinputstream and filteroutputstream are the parent classes of all filtered input and output streams, respectively.

In order to use a filter stream, you must first connect the filter stream to an input / output stream, usually by specifying the input / output stream to be connected in the parameters of the construction method. For example: filterinputstream (InputStream in);   FilterOutputStream( OutputStream out );

Several common filter streams:

4.7 character stream processing

Java provides classes that handle character streams represented by 16 bit Unicode codes, that is, a series of classes derived from the base classes reader and writer. 4.7.1 reader and writer

These two classes are abstract classes. They only provide a series of interfaces for character stream processing. They cannot generate instances of these two classes. They can only process character streams by using subclass objects derived from them. 1. Reader class is the parent class of all character stream input classes. ◇ read the character public int read() throws IOException// Read a character, and the return value is the read character public int read (char cbuf []) throws IOException/* Read a series of characters into the array cbuf [], and the return value is the number of characters actually read * / public abstract int read (char cbuf [], int len) throws IOException; / * Read len characters and store them from the subscript off of the array cbuf []. The return value is the actual number of characters read. This method must be implemented by subclasses (because it is an abstract method, otherwise the class must be declared as an abstract class) * / ◇ tag stream public Boolean marksupported()// Judge whether the current flow supports marking public void mark (int readaheadlimit) throws IOException; / / mark the current stream and support backtracking of readaheadlimit characters at most.   public void reset() throws IOException; // Reset the current flow to the marked position ◇ close the flow public abstract void close() throws IOException; 2. The writer class is the parent class of the output class that handles all character streams. ◇ write the character public void write (int c) throws IOException to the output stream; / / write the lower 16 bits of the integer value C to the output stream public void write (char cbuf []) throws IOException; / / write the character array cbuf [] to the output stream public abstract void write (char cbuf [], int len) throws IOException; / / write the len characters in the character array cbuf [] from the position with the index off to the output stream public void write (string STR) throws IOException; / / write the characters in the string STR to the output stream public void write (string STR, int len) throws IOException; / / write len characters from the index off in the string STR to the output stream ◇ flush() clears the output stream and outputs all cached bytes. ◇ close the flow public abstract void close() throws IOException;

4.7.2 inputstreamreader and outputstreamwriter Java The most basic class used to process character stream in io package, which is used as an intermediary between byte stream and character stream.

4.7.3 BufferedReader and bufferedwriter

◇ generate the flow object public BufferedReader (reader in)// Use the default buffer size public BufferedReader (reader in, int SZ)// SZ is the size of the buffer, public bufferedwriter (writer out);   public BufferedWriter(Writer out,int sz); ◇ read / write characters in addition to the basic reading and writing methods provided in reader and writer, the processing of the whole line of characters is added.   public String readLine() throws IOException; // Read a line of characters public void newline() throws IOException// Write a line of characters

[example 4-4] inputstreamreader IR; BufferedReader in; IR = new inputstreamreader (system. In) ; / / receives a string input from the keyboard and creates an object of character input stream. The definition of in / / is as follows: public static final InputStream in, and the definition of output stream out is as follows: public static final / / printstream out in = new BufferedReader (IR);       String s=in. readLine(); / / read a line from the input stream in and assign the read value to the string variable s system out. println("Input value is: "+s); Note: when reading the character stream, if it is not from the local, for example, from a machine somewhere on the network with a different local encoding method, we cannot simply use the local default encoding method when constructing the input stream, otherwise the read characters will be incorrect; In order to correctly read the characters on the heterogeneous machine, we should construct the input stream object in the following way: IR = new inputstreamreader (is, "8859_1"); Adopt ISO 8859_ 1 coding method, which is a coding method mapped to ASCII code, and can correctly convert characters between different platforms.

4.8 serialization of objects

4.8.1 definition of serialization

4.8.2 serialization method in Java In the IO package, the interface serializable is used as a tool to realize object serialization. Only objects of classes that implement serializable can be serialized

4.9 other commonly used flows

4.9.1 pipeline flow

A pipe is used to connect the output of one program, thread, or block of code to the input of another program, thread, or block of code.

The pipeline input stream is used as the receiving end of a communication pipeline, and the pipeline output stream is used as the sending end. Before using a pipe, the pipe output stream and the pipe input stream must be connected. There are two connection methods: 1. Connect pipedinputstream (pipedoutputstream SRC) in the construction method;   PipedOutputStream(PipedInputStream snk); 2. Connect () method is used to connect. The class pipedinputstream is defined as: void connect (pipedoutputstream SRC); Class pipedoutputstream is defined as: void connect (pipedinputstream SNK);

1. Bytearrayinputstream and bytearrayoutputstream bytearrayinputstream / / read data in bytes from the byte array bytearrayoutputstream / / write data in bytes to the byte array 2. Stringbufferinputstream and stringbufferoutputstream stringbufferinputstream / / read data from the string buffer StringBuffer Data in characters stringbufferoutputstream / / writes data in characters to the string buffer StringBuffer

Sequenceinputstream connects several input streams in sequence. Sequential input stream provides the function of unifying several different streams into the same stream, which makes the program more concise.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>