Fourth lecture Java exception handling and IO stream

xiaoxiao2021-03-06  57

[Before class thinking] 1. What is exception? Which two exception processing mechanisms in Java? 2. What is the base stream and the base class of the character stream? 3. What is the active serialization? What is the role of the object serialization?

Difficulties: 1. How to use two exceptional processing mechanisms in Java, discard exceptions and declaration to abandon exceptional differences. 2. When processing a character stream, the parameters of its constructor are one byte stream. 3. Object serialization concept. 4.1 What is exception

4.1.2 Exception Processing Mechanism

Abandoned (throw): In the implementation of the Java program, an exception object is generated if an exception event occurs. The generated exception object will be passed to the Java runtime system, which is referred to as an abandonment (throw) exception.

Two mechanisms of two processing exceptions: ◇ Capture exception: When the Java runtime system gets an exception object, it will travel back along the method of calling, looking for the code to handle this exception. After finding the exception of this type of exception, the runtime system handles the current exception object to this method, which is called capture (CATCH). This is a positive exception processing mechanism. If the system does not capture exceptions when the system is running, the system will terminate, and the corresponding Java program will exit. ◇ 声 Discourse Exception: If a method does not know how to handle the exceptions you appear, you can declare the abandonment exception when the method declares. This is a negative exception processing mechanism.

4.1.3 Levels of Exceptions In JDK, each package defines exception classes, and all exception categories are directly or indirectly in the Throwable class. Figure 4-1 is the inheritance relationship of exception class in JDK.

The exception class in Java can be divided into two major categories: Error dynamic link failed, virtual machine error, etc., usually Java programs should not capture such exceptions, and will not abandon this exception. Exception 1) Runtime Exception: Inherited by the class of RuntimeException is a runtime exception, such as arithmetic exceptions (divided zero), array under terracotae exceptions, etc. Since these exceptions generated are unknown, the Java compiler allows programmers to process them in programs. 2) Non-run exception: Other exceptions from Exception inheritance in addition to runtime exceptions, such as FilenotFoundException (files are not found). The Java compiler requires that this exception must be processed in the program, capture exceptions or declaration to discard exception.

4.2 Exception Process 4.2.1 Capture Exception Capture Exception is achieved by try-catch-finally statement:

Try {...} catch (exceptionname1 e) {...} catch (exceptionname2 e) {...} ...} finally {... } ◇ TRY Capture Exception The first step is to use the Try {...} to select the range of exceptions, and the statements in the code block defined by TRY may generate an exception object and abandon. ◇ CATCH Each TRY code block can be accompanied by one or more CATCH statements to handle the exceptions generated in the TRY code block. The catch statement only needs one formal parameter to indicate the exception type it can capture. This class must be the subclass of the throwable, and the runtime system passes the abandoned exception object to the Catch block by parameter values. In the CATCH block, the code for processing the exception object, like accessing other objects, can access the variable of an exception object or a method of calling it. GetMessage () is the method provided by THROWABLE to get information about exception events. The class throwable provides Method PrintStackTrace () to track the contents of the stack when the exception event occurs. For example: try {...} catch (filenotfoundexception e) {system.out.println (e); System.out.Println ("Message:" E.GetMessage ()); E.PrintStackTrace (System. OUT;} catch (ioException e) {system.out.println (e);} Catch statement sequence: capture the order of exceptions and the order of the CATCH statement, when capturing an exception, the rest of the Catch statement is not Match again. Therefore, when scheduled the order of the CATCH statement, first, the most special exception should be captured, and then gradually generalize. That is, it is generally arranged first, and then arrange the parent class. ◇ Finally Capture Exception The final step is to provide a unified exit with the Finally statement for exception, so that the status of the program can be managed to be managed before the control flow transfer to the program. The statement in the Finally block is executed regardless of whether an exception event occurs in the TRY code block. 4.2.2 Declaration Abandon Exception

1. Declaration Abandon Exception If an exception is generated in one method, this method does not know how to process this exception event. At this time, a method should declare the except for abandonment, so that exceptions can be from the call stack Communicate backward until there is a suitable method to capture it. The declaration discarding exception is indicated in the ThROWS clause in a method statement. For example: public int iexception {......} The Throws clause can specify multiple exceptions, between the comma. For example: public static void main (string args []) throws ioException, indexoutofboundsexception {...} 2. Throwing exceptions is the process of generating exception objects, first generating exception objects, exceptions, or generated by virtual machines, or generated by instances of certain classes, or can be generated in the program. In the method, the exception object is thrown through the Throw statement. For example: ioException e = new oException (); throw e; Excellence that can be thrown must be a case of throwable or its subclasses. The following statement will generate syntax errors when compiling: Throw new string; 4.3 Custom Exceptional class

Custom exceptions must be Direct or indirects of Throwable. Note: The exception to the abandonment of a method is existing as part of this method and the external interaction. Therefore, the caller of the method must understand these exceptions and determine how to process them correctly.

4.4 I / O flow Overview Input / Output Processing is a very important part of the program design, such as reading data from the keyboard, reading data from the file or writing data to the file, etc. Java puts these different types of inputs, output source abstraction (stream), expressed with a unified interface, so that the program is simply understood. JDK provides package java.io, including a series of classes to implement input / output processing. Below we will introduce the content of the Java.IO package.

4.4.1 Level 1 of I / O stream 1. Byte stream: A series of classes derived from InputStream and OutputStream. This type of stream is based on byte (byte). ◇ InputStream, OutputStream ◇ FileInputStream, FileOutputStream ◇ PipedInputStream, PipedOutputStream ◇ ByteArrayInputStream, ByteArrayOutputStream ◇ FilterInputStream, FilterOutputStream ◇ DataInputStream, DataOutputStream ◇ BufferedInputStream, BufferedOutputStream 2. Character flow: A series of classes derived from Reader and Writer, such streams are based on the characters represented by 16-bit Unicode code. ◇ Reader, Writer ◇ InputStreamReader, OutputStreamWriter ◇ FileReader, FileWriter ◇ CharArrayReader, CharArrayWriter ◇ PipedReader, PipedWriter ◇ FilterReader, FilterWriter ◇ BufferedReader, BufferedWriter ◇ StringReader, StringWriter 3. Object flow ◇ ObjectInputStream, ObjectOutputStream 4. Other ◇ Document processing: file, randomaccessfile; ◇ interface DataInput, Dataoutput, ObjectInput, ObjectOutput; 4.4.2 InputStream and OutputStream

1. INPUTSTREAM ◇ Read data from the stream: int (); // Read one byte, return the value to the read byte Int read (Byte B []); // Read multiple bytes, place it to In byte array B, the number of bytes typically // reads the length of B, the return value is the number of bytes of the actual // Int Read (Byte B [], INT OFF, INT LEN); // Read the LEN byte, place / / // 到 标 开始 开始 字 字 开始 开始 开始, 数,,, 未 未 未 未 流 未 流 未 流 未The number of bytes read long Skip (long n); // read pointer skips n bytes not reading, return the value of the actual // Skip Number of bytes ◇ Turn off the stream: close (); // After the operation is completed, it must be turned off to use the mark in the input stream: Void Mark (Int Readlimit); // Record the location where the current read pointer is located, readlimit // indicates the pointer position tagged after the read pointer reads the readlimit byte. Failure vid reset (); // Re-point the read pointer to the location Boolean Marksupported (); // current stream supports the recording function 2 of the read pointer 2. OutputStream ◇ Output data: Void Write (int b) Write a byte b void write in the flow in the flow (byte b []); // Write a byte array B Void Write in the traffic (byte B [], INT OFF, INT LEN; // Start from // from // from //, write the stream in the byte of the LEN, and output all cached. Bytes Since some stream support cache functions, this method will enforce all content in the cache into the stream. ◇ Close the stream: close (); // must close the exceptions in 4.4.3 I / O after completion

I / O exceptions may occur when I / O operations, which belong to the exception of non-running, should be processed in the program. Such as: FilenotFoundException, EOFEXCEPTION, IOEXCEPTION.

4.5 file processing

In I / O processing, the most common is the operation of files, and the classes related to files in Java.IO packages are: File, FileInputStream, FileoutputStream, RamdomAccessFile, and FileDescriptor; interfaces are: FileNameFilter. 4.5.1 File Description The class file provides an attribute that describes a file object-independent manner. Below we introduce the various methods provided in the File.

◇ ◇ File or directory generation public file (String Path); / * If the path is the actual existing path, the file object / * represents a directory; if Path is the file name, the file object is represented by the file. * / Public file (string path, string name); // path is the path name, name is the file name public file (file dir, string name); // Dir is the path name, name is the file name ◇ file name processing string String GetName (); // Get a file name (excluding the path) string getPath (); // Get the path name of a file String getabsolutePath (); // Get a file's absolute path name string getParent (); // Get the previous directory name String RenameTo (file newname); // Create the current file name to the full path of the given file ◇ File Properties Test Boolean EXISTS (); // Test if the file indicated by the current File object is There is boolean canwrite (); // test whether the current file can be written to write Boolean canread (); // Test whether the current file reads Boolean isfile (); // Test whether the current file is a file (not directory) Boolean isDirectory (); / / Test whether the current file is a directory ◇ Ordinary file information and tool long lastmodified (); // Get the time of the file last modified time long length (); // Get the length of the file, in bytes, Boolean delete (); / / Delete the current file ◇ directory operation Boolean mkdir (); // Generate a path string list () specified by the object (), // listing the files in the current directory in the WINDOWS programming programming, directory : File Dir = New File ("E: // myApp // src"); 4.5.2 Document processing class fileInputStream and FileOutStream are used to perform file I / O processing, and the methods provided by them can open local The files on the host and perform sequential read / write. For example, the following statement segment is the content in the file named text, and is displayed on the console until the file ends.

FileInputStream Fis; try {fis = new fileinputstream ("text"); system.out.print ("Content of text is:"); int b; while ((b = fis.read ())! = - 1) / / Sequentially read the contents of the file text and assign the value to the integer variable B until the file ends. {System.out.print ((char) b);}} catch (filenotfoundexception e) {system.out.println (e);} catch (ooexception e) {system.out.println (e);} 4.5 .3 Random Access Documents For InputStream and OutputStream, their instances are all sequential traffic, that is, only files can be read / written in order. Random access files allow random read / write to file content. In Java, class randomaccessfile provides a method of random access files. The declaration of the class randomaccessfile is: public class randomaccessfile Extends Object IMPLEments DataInput, the method defined in the DataOutput interface DataInput mainly includes reading the basic type of data from the stream, reading a line of data, or reading the number of bytes of the specified length. Such as: readboolean (), readint (), readline (), readfully (), etc. The methods defined in interface DataOutput are primarily written to the basic type of data, or write a range of bytes of lengths. Such as: Writechar (), WriteDouble (), Write (), etc. The method in the RandomaccessFile class is described in detail below. ◇ Structure: RandomaccessFile (String Name, String Mode); // Name is a file name, Mode // is open mode, such as "R" means read-only, "RW" means readable, "randomaccessfile (File File" Mode); // file is the operation of the file object ◇ file pointer LONG getFilePointer (); // Used to get the current file pointer Void seeker (long POS); // Used to move file pointer to the specified location int Skipbytes (int Skipbytes " n); // Make the file pointer forward to the specified n byte

4.6 filtering flow

The filter flow can be processed on the data while reading / writing data. It provides a synchronization mechanism that allows only one thread to access an I / O stream at a certain moment to prevent multiple threads while operating the I / O stream. The unexpected result is brought. Class FilterInputStream and FilterOutputStream are respectively the parent class for all filtration input streams and output streams, respectively.

In order to use a filter flow, you must first connect the filter flow to an input / outflow, usually achieved by specifying the input / outflow to be connected in the parameters of the constructor. For example: FILTERINPUTSTREAM (InputStream IN); FilterOutputStream

Several common filters:

◇ BufferedInputStream and BufferedOutputStream buffer flow to improve the efficiency of input / output processing. ◇ DataInputStream and DataOutputStream not only read / write data streams, but also read / write the basic type of Java language, such as: Boolean, Int, Float, etc. ◇ LINENUMBERINPUTSTREAM In addition to providing support for input processing, LINENUMBERINPUTSTREAM can record the current line number. ◇ PushbackInputStream provides a way to return the originally read bytes to the input stream to re-read it again. ◇ The role of the PrintStream print flow is to send the internal structure of the Java language to the corresponding output stream in its character representation. 4.7 Character flow processing

Java provides a class that depends on the character stream represented by 16-bit Unicode code, which is a series of classes that are derived from Reader and Writer as base classes. 4.7.1 Reader and Writer

These two classes are abstract classes, just provide a series of interfaces for character stream processing, unable to generate these two classes, can only process the character stream by using sub-objects they derived. 1. The Reader class is the parent class that handles all character streams. ◇ Read Character Public Int Read () THROWS IOEXCEPTION; // Read a character, return the value read the character public int ie (char CBUF []) throws ioException; / * Read a series of characters to array CBUF [] In, the return value is the number of characters actually read * / public abstract int iexception; / * reads the LEN character, from the array CBUF [] subscript OFF Start storage, return value is the number of characters actually read, this method must be implemented by subclass (because it is an abstract method, the class must declare an abstract class) * / ◇ Mark current (); // Judgment Current Whether the stream supports Mark Public Void Mark (Int ReadaheadLimit "for IOException; // gives the current stream, supporting the backtrack of ReadaheadLimit characters. Public void reset () throws ioException; // Reduces the current stream to the Monitor ◇ Close the flow public abstract void close () throws oException; 2. The Writer class is the parent class that handles all character stream output classes. ◇ 入 输 入 i 入 i 向 i 向 低 16 16 16 b (; (; c;;;;;;;;; 入;;;;;;;;;;;;;;;;; [] Write output flow Public Abstract Void Write (CHAR CBUF [], int OFF, int LEN) THROWS IOEXCEPTION; // Write the output from the LEN character starting from the index of OFF positions in the character array Stream Public Void Write (String Str) THROWS IOEXCEPTION; / / Write the character string STR to the output stream public void write (string str, int off, int LEN) throws ioException; // Put the string STR from index OFF The LEN character written in the beginning is written. ◇ Turn off the flow of public abstract void close () throws ioException; 4.7.2 InputStreamReader and OutputStreamWriter Java.IO Packets The most basic classes used to handle the word stream, which are used as an intermediary between byte streams and character streams.

◇ Generating flow objects Public InputStreamReader (InputStream IN); / * in is a byte stream, and the InputStreamReader is a character stream, but its source is byte stream IN, so INPUTSTREAMReader can convert byte stream in converted into a word stream process. / * Public InputStreamReader (InputStream In, String ENC) throws unsupportedEncodingexception; / * ENC is an encoding method, which is encoded when the byte stream is converted to the character stream, such as ISO8859-1, UTF-8, UTF-16 etc. * / public OutputStreamWriter (OutputStream out); / * out stream of bytes, and the stream of characters is OutputStreamReader * / public OutputStreamWriter (OutputStream out, String enc) throws UnsupportedEncodingException; // enc InputStreamReader coding method and the OutputStreamWriter: ◇ Read and write characters Basically with Reader and Writer. ◇ Get the current encoding method public string getencoding (); ◇ Close the flow public void close () throws ioException; 4.7.3 BUFFEREDReader and BufferedWriter

◇ Generate flow object public bufferedreader (Reader IN); // uses the default buffer size public buffereader (// sz is the size of the buffer PUBLIC BUFFEREDWRITER (Writer Out); Writer Out INT SZ); ◇ Read / write characters In addition to the basic read and write methods provided in Reader and Writer, the processing of the entire line is increased. Public string readline () throws oException; // read a line of characters public void newline () throws oException; // Write a line of characters

[Example 4-4] InputStreamReader Ir; BufferedReader In; IR = New InputStreamReader (System.IN); // Receive a string input from the keyboard, and created a character input stream object, IN's fixed // righteous As follows: Public Static Final InputStream IN, the output stream OUT is defined as follows: public static final // printStream out in = new bufferedreader (IR); string s = in.readline (); // Read a line from the input stream in in the input stream, 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, such as a network Somewhere with local coding methods different machines, then we cannot simply use local default encoding mode when constructing input flow, otherwise the characters read are incorrect; in order to correctly read the characters on the hetero machine, we The input stream object should be constructed using the following manner: IR = New InputStreamReader (IS, "8859_1"); use ISO 8859_1 encoding mode, this is a coding method that maps to the ASCII code, which can correctly convert characters between different platforms. 4.8 Serialization of the object

4.8.1 Definition of Serialization

1. What is the life of the serialized object typically terminates with the termination of the program that generates the object. Sometimes, you may need to save the status of the object and restore the object when you need it. We use this object to record your own state to reproduce the ability to regenerate, called the persistence of the object. The object records yourself by writing a value that describes its state, the serialization of the object.

2. Serialized purpose serialization is to provide a set of features for Java's operating environment, and its main task is to write the value of the object instance variable.

4.8.2 Serialization Method In java.io packet, interface serializable is used as a tool for realizing the serialization of the object, and only the object that implements the class of Serializable can be serialized.

1. Define a serializable object public class student imports serializable {int id; // student number string name; // Name int agent // 系 年 d d别, String department) {this.id = id; this.name = name; this.Department = department;}} 2. The input / output stream of the constructor is to serialize an object, and must be associated with a certain object input / output stream, saving the object state by the object output stream, recovering the object state by the object input stream. In the Java.IO package, ObjectInputStream and ObjectOutputStream are provided to extend data stream functions to readable and write objects. Using the ReadObject () method in ObjectInputStream, you can directly read an object, using the WriteObject () method in the ObjectOutputStream can save the object to the output stream. Student stu = new Student (981036, "Liu Ming", 18, "CSD"); FileOutputStream fo = new FileOutputStream ( "data.ser"); // save the state of the object ObjectOutputStream so = new ObjectOutputStream (fo); try { so.writeObject (stu); so.close ();} catch (IOException e) {System.out.println (e);} FileInputStream fi = new FileInputStream ( "data.ser"); ObjectInputStream si = new ObjectInputStream (fi ); // Restore the status of the object Try {stu = () Si.readObject (); Si.close ();} catch (ioException e) {system.out.println (e);} In this example, we First define a class Student, implement the serializable interface, and then save the Student object to the file data.ser by the WriteObject () method of the object output stream. Thereafter, the readObject () method of the object input stream is read from the file data.ser. 4.8.3 Precautions for Serialization

1. The serialized energy saved can only save the non-statistial member variable of the object, and any member method and static member variable cannot be saved, and the serialization is only the value of the variable, and no modifiers of the variable cannot be saved. . 2. TRANSIENT Keyword For some types of objects, its status is instantaneous, such objects cannot save their status, such as a Thread object, or a fileInputstream object, for these fields, we must use the transient keyword, see 3.2 .1 section 3. Customized serialization mechanisms, object serialization first writes information about class data and class fields, and then writes its value in order of the raised arrangement of the name. If you want to clearly control the write order and writing types of these values, you must define your own way you read the data stream. That is to rewrite the WriteObject () and readObject () method of the interface serializeble in the definition of the class. For example, in an example of 4.8.2, the overwritten WriteObject () and ReadObject () method can be added to customize its serialization. private void writeObject (ObjectOutputStream out) throws IOException {out.writeInt (id); out.writeInt (age); out.writeUTF (name); out.writeUTF (department);} private void readObject (ObjectInputStream in) throws IOException {id = in.readint (); agn = in.readint (); name = in.readutf (); department = in.readutf ();} 4.9 Other common streams

4.9.1 Pipeline

The pipe is used to connect an output of a program, thread or code block to another program, thread, or code block.

The pipe input stream acts as a receiving end of a communication pipe, and the pipe output flow is an transmitting end. The pipe output stream and the pipe input stream must be connected before using the pipe. There are two ways to connect below: 1. Connect PiPedInputStream (PipedputStream SRC) in the construction method; PiPedOutputStream (PipedInputStream SNK); 2. Connect () method Connect the connection class PipedInputStream as: Void Connect (PiPedOutputStream SRC); Class PiPedOutputStream is defined as: Void Connect (PipedInputStream SNK);

4.9.2 Memory Read / Write

1. ByteArrayInputStream and ByTearRayoutputStream BYTEARRAYINPUTSTREAM // Read data in bytes in bytes in byte arrays byterrayoutputstream // written in bytes in bytes 2. StringBufferInputStream and StringBufferoutputStream StringBufferInputStream // Read data in characters in the string buffer StringBuffer StringBufferoutputStream // Write data in character units in the string buffer StringBuffer

4.9.3 Sequential input stream

转载请注明原文地址:https://www.9cbs.com/read-118245.html

New Post(0)