Java zero-based learning 023-API advanced fourth day

API-day04

buffered character stream

Buffered character output stream: java.io.PrintWriter

java.io.BufferedWriter和BufferedReader

There is also a buffer inside the buffered character stream, and the read and write text data can be read and written in blocks to speed up the efficiency. And the buffered stream has a special function: it can read and write text data by line.

java.io.PrintWriter has a buffered character output stream with automatic row refresh, which is more commonly used in actual development. It will always automatically connect BufferedWriter internally as a block write acceleration.

insert image description here

package io;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * 缓冲字符流
 * 缓冲字符流是一对高级流,在流连接中的作用是提高读写文本数据的效率,并且
 * 可以安行读写字符串.
 * java.io.BufferedReader和BufferedWriter
 *
 * 实际开发中缓冲字符输出流我们更常用的是PrintWriter,具有自动行刷新功能
 * 的缓冲字符输出流,其内部总是连接BufferedWriter作为缓冲加速使用.
 */
public class PWDemo1 {
    
    
    public static void main(String[] args) throws FileNotFoundException {
    
    
        /*
            PrintWriter提供了对文件操作的构造方法:
            PrintWriter(String path)
            PrintWriter(File file)
         */
        //向文件中写入字符串
       	PrintWriter pw = new PrintWriter("pw.txt");
        pw.println("super idol的笑容都没你的甜。");
        pw.println("八月正午的阳光都没你耀眼。");
        System.out.println("写出完毕!");
        pw.close();

    }
}
Use PW in streaming link
package io;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 在流连接中使用PrintWriter
 */
public class PWDemo2 {
    
    
    public static void main(String[] args) throws FileNotFoundException {
    
    
        //如果希望有追加模式,则需要自行创建文件输出流并指定
        FileOutputStream fos = new FileOutputStream("pw.txt",true);
        //在转换流上加上字符集,可以按照指定字符集写出。
        OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
        BufferedWriter bw = new BufferedWriter(osw);
        /*
            当PrintWriter第一个参数为流时,我们就支持再传入一个boolean值参数,如果该值为true则
            打开了自动行刷新功能。每当我们调用println方法后就会自动flush一次
            注意:调用print方法并不会自动flush!!!!!!!
         */
        PrintWriter pw = new PrintWriter(bw,true);

//        FileOutputStream fos = new FileOutputStream("pw.txt",true);
//        BufferedOutputStream bw = new BufferedOutputStream(osw);
        /*
            不要将PW直接链接在缓冲字节输出流上,因为PW内部总是链接这BW这个缓冲字符输出流了。
            不需要在缓冲字节流上再缓冲了,会降低效率
         */
//        PrintWriter pw = new PrintWriter(bw);

        Scanner scanner = new Scanner(System.in);
        while(true) {
    
    
            String line = scanner.nextLine();
            if("exit".equalsIgnoreCase(line)){
    
    
                break;
            }
            pw.println(line);
        }
        System.out.println("写出完毕!");

        pw.close();

    }
}
PrintWriter's Automatic Line Refresh Feature

If the first parameter is a stream when instantiating PW, you can pass in another boolean parameter at this time. When the value is true, the automatic row refresh function is enabled. That is: whenever we use the println method of PW to write a line of strings, it will be automatically flushed.

package io;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 在流连接中使用PrintWriter
 */
public class PWDemo2 {
    
    
    public static void main(String[] args) throws FileNotFoundException {
    
    
        //如果希望有追加模式,则需要自行创建文件输出流并指定
        FileOutputStream fos = new FileOutputStream("pw.txt",true);
        //在转换流上加上字符集,可以按照指定字符集写出。
        OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
        BufferedWriter bw = new BufferedWriter(osw);
        /*
            当PrintWriter第一个参数为流时,我们就支持再传入一个boolean值参数,如果该值为true则
            打开了自动行刷新功能。每当我们调用println方法后就会自动flush一次
            注意:调用print方法并不会自动flush!!!!!!!
         */
        PrintWriter pw = new PrintWriter(bw,true);

//        FileOutputStream fos = new FileOutputStream("pw.txt",true);
//        BufferedOutputStream bw = new BufferedOutputStream(osw);
        /*
            不要将PW直接链接在缓冲字节输出流上,因为PW内部总是链接这BW这个缓冲字符输出流了。
            不需要在缓冲字节流上再缓冲了,会降低效率
         */
//        PrintWriter pw = new PrintWriter(bw);

        Scanner scanner = new Scanner(System.in);
        while(true) {
    
    
            String line = scanner.nextLine();
            if("exit".equalsIgnoreCase(line)){
    
    
                break;
            }
            pw.println(line);
        }
        System.out.println("写出完毕!");

        pw.close();

    }
}

buffered character stream

Buffered character input stream: java.io.BufferedReader

It is an advanced character stream, characterized by reading text data in blocks, and can read strings by line.

package io;

import java.io.*;

/**
 * 使用缓冲字符输入流java.io.BufferedReader读取文本数据
 * 缓冲字符输入流是一个高级流,有两个主要功能:
 * 1:块读文本数据加速
 * 2:可以按行读取字符串
 */
public class BRDemo {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //将当前源代码输出到控制台上
        FileInputStream fis = new FileInputStream("./src/io/BRDemo.java");
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader br  = new BufferedReader(isr);
        String line;
        /*
            BufferedReader的readLine方法是它的独有方法,作用是读取一行字符串
            该方法返回的字符串不包含最后的换行符。如果读取了一个空行(这一行只有换行符),那么
            返回值为空字符串,即:""。如果返回值为null则表示流读取到了末尾。
         */
        while((line = br.readLine()) != null) {
    
    
            System.out.println(line);
        }
        br.close();
    }
}
IOSummary

I流

exception handling

Java exception handling mechanism

  • The superclass of all errors in java is: Throwable. There are two subclasses under it: Error and Exception
  • The subclasses of Error describe system errors, such as virtual machine memory overflow.
  • The subclasses of Exception describe program errors, such as null pointers, out-of-bounds in the following table, and so on.
  • Usually the exceptions handled in our program are Exception.

try-catch in exception handling mechanism

package exception;

/**
 * 异常处理机制中的try-catch
 * 语法:
 * try{
 *     可能出现异常的代码片段
 * }catch(XXXException e){
 *     try中出现XXXException后的处理代码
 * }
 *
 * try语句块不能独立存在,后面必须跟catch语句块或finally语句块
 */
public class TryCatchDemo {
    
    
    public static void main(String[] args) {
    
    
        System.out.println("程序开始了");
        try {
    
    
//            String line = null;
//            String line = "";
            String line = "abc";
            //当JVM执行程序出现了某个异常时就会实例化这个异常并将其抛出
            //如果该异常没有被异常处理机制控制,则JVM会将异常隐式抛出当方法外(这里是main方法外)
            System.out.println(line.length());
            System.out.println(line.charAt(0));
            System.out.println(Integer.parseInt(line));
            //若try语句块中某句话出错了,则剩下的代码都不会执行!
            System.out.println("!!!!!!!!!!!!!!!!");


//        }catch(NullPointerException e){
    
    
//            System.out.println("出现了空指针!");
//        //catch可以定义多个,当try中不同的异常有不同处理办法时可分开捕获并处理
//        }catch(StringIndexOutOfBoundsException e){
    
    
//            System.out.println("出现了下标越界!");
        //若某些异常的处理方式相同时,可以合并在一个catch来处理
        }catch(NullPointerException|StringIndexOutOfBoundsException e){
    
    
            System.out.println("出现了空指针或下标越界并处理了!");
        //可以在下面catch超类异常来捕获并处理这一类异常。
        }catch(Exception e){
    
    
            System.out.println("反正就是出了个错");
        }

        System.out.println("程序结束了");

    }
}

finally in the exception handling mechanism

  • The finally block defines the last block in the exception handling mechanism. It can be directly after the try, or after the last catch.
  • finally can guarantee that as long as the program is executed in the try statement block, no matter whether the code in the try statement block is abnormal or not, finally it must be executed in the end.
  • finally is usually used to do operations such as releasing resources.
package exception;

/**
 * 异常处理机制中的finally块
 * finally块定义在异常处理机制中的最后一块。它可以直接跟在try之后,或者最后一个catch之后。
 *
 * finally可以保证只要程序执行到了try语句块中,无论try语句块中的代码是否出现异常,最终
 *  finally都必定执行。
 *
 * finally通常用来做释放资源这类操作。
 */
public class FinallyDemo {
    
    
    public static void main(String[] args) {
    
    
        System.out.println("程序开始了...");
        try{
    
    
            String line = "abc";
//            String line = null;
            System.out.println(line.length());
            return;
        }catch(Exception e){
    
    
            System.out.println("出错了!");
        }finally{
    
    
            System.out.println("finally中的代码执行了!");
        }
        System.out.println("程序结束了!");
    }
}

Application of exception handling mechanism during IO operation

package exception;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * IO操作时的异常处理机制应用
 */
public class FinallyDemo2 {
    
    
    public static void main(String[] args) {
    
    
        FileOutputStream fos = null;
        try {
    
    
            fos = new FileOutputStream("fos.dat");
            fos.write(1);
        } catch (IOException e) {
    
    
            e.printStackTrace();//向控制台输出当前异常的错误信息
        } finally {
    
    
            try {
    
    
                if (fos!=null) {
    
    
                    fos.close();
                }
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

Auto Shutoff Feature

After JDK7, java provides a new feature: automatic shutdown. It is intended that the exception handling mechanism can be used more concisely in the IO operation to complete the final close operation.

语法:
try(
   	定义需要在finally中调用close()方法关闭的对象.
){
    
    
    IO操作
}catch(XXXException e){
    
    
    ...
}

In the above syntax, the objects that can be defined and initialized in the "()" of try must implement the java.io.AutoCloseable interface, otherwise the compilation will fail.

public class AutocloseableDemo {
    public static void main(String[] args) {
        try(
                FileOutputStream fos = new FileOutputStream("fos.dat");
        ){
            fos.write(1);
        } catch (IOException e) {
            e.printStackTrace();//向控制台输出当前异常的错误信息
        }
    }
}

The above code is recognized by the compiler, not the virtual machine. After the compiler compiles the above code, it will change back to the code of the FinallyDemo2 case in the compiled class file (the last case of the last class).

throw keyword

Throw is used to actively throw an exception externally. Usually, we actively throw an exception externally in the following two situations:

  • 1: When the program encounters a program that satisfies the grammar but does not meet the business requirements, it can throw an exception to inform the caller.
  • 2: Program execution encountered an exception, but the exception should not be thrown to the caller when the current code fragment is resolved.
package exception;

/**
 * 测试异常的抛出
 */
public class Person {
    
    
    private int age;

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) throws Exception {
    
    
        if(age<0||age>100){
    
    
            //使用throw对外抛出一个异常
            throw new RuntimeException("年龄不合法!");
        }
        this.age = age;
    }
}
package exception;

/**
 * throw关键字,用来对外主动抛出一个异常。
 * 通常下面两种情况我们主动对外抛出异常:
 * 1:当程序遇到一个满足语法,但是不满足业务要求时,可以抛出一个异常告知调用者。
 * 2:程序执行遇到一个异常,但是该异常不应当在当前代码片段被解决时可以抛出给调用者。
 */
public class ThrowDemo {
    
    
    public static void main(String[] args) {
    
    
        Person p = new Person();
        p.setAge(10000);//符合语法,但是不符合业务逻辑要求。
        System.out.println("此人年龄:"+p.getAge());
    }
}

throws keyword

When using throw in a method to throw a non-RuntimeException exception, it is necessary to use throws on the method to declare the throwing of this exception. At this time, the code that calls this method must handle this exception, otherwise the compilation will fail.

package exception;

/**
 * 测试异常的抛出
 */
public class Person {
    
    
    private int age;

    public int getAge() {
    
    
        return age;
    }

    /**
     * 当一个方法使用throws声明异常抛出时,调用此方法的代码片段就必须处理这个异常
     */
    public void setAge(int age) throws Exception {
    
    
        if(age<0||age>100){
    
    
            //使用throw对外抛出一个异常
//            throw new RuntimeException("年龄不合法!");
            //除了RuntimeException之外,抛出什么异常就要在方法上声明throws什么异常
            throw new Exception("年龄不合法!");
        }
        this.age = age;
    }
}

When we call a method that contains a throws statement to throw an exception, the compiler requires us to handle the exception, otherwise the compilation will fail. There are two processing methods:

  • Use try-catch to catch and handle this exception
  • Continue to use throws on the current method (in this case, the main method) to declare that the exception is thrown for the caller to resolve. The specific choice depends on the responsibility of exception handling.
package exception;

/**
 * throw关键字,用于主动对外抛出一个异常
 */
public class ThrowDemo {
    
    
    public static void main(String[] args){
    
    
        System.out.println("程序开始了...");
        try {
    
    
            Person p = new Person();
            /*
                当我们调用一个含有throws声明异常抛出的方法时,编译器要求
                我们必须添加处理异常的手段,否则编译不通过.而处理手段有两种
                1:使用try-catch捕获并处理异常
                2:在当前方法上继续使用throws声明该异常的抛出
                具体用哪种取决于异常处理的责任问题
             */
            p.setAge(100000);//典型的符合语法,但是不符合业务逻辑要求
            System.out.println("此人年龄:"+p.getAge()+"岁");
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }

        System.out.println("程序结束了...");
    }
}

Note that throws should never be used on the main method!!

Rules when methods containing throws are overridden by subclasses

package exception;

import java.awt.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 子类重写超类含有throws声明异常抛出的方法时对throws的几种特殊的重写规则
 */
public class ThrowsDemo {
    
    
    public void dosome()throws IOException, AWTException {
    
    }
}
class SubClass extends ThrowsDemo{
    
    
//    public void dosome()throws IOException, AWTException {}

    //可以不再抛出任何异常
//    public void dosome(){}

    //可以仅抛出部分异常
//    public void dosome()throws IOException {}

    //可以抛出超类方法抛出异常的子类型异常
//    public void dosome()throws FileNotFoundException {}

    //不允许抛出额外异常(超类方法中没有的,并且没有继承关系的异常)
//    public void dosome()throws SQLException {}

    //不可以抛出超类方法抛出异常的超类型异常
//    public void dosome()throws Exception {}
}

Summarize

buffered character output stream

Buffered character output streams need to remember PrintWriter and BufferedReader

effect:

1: Block write or block read text data acceleration

2: You can write or read strings by line

java.io.PrintWriter a buffered character output stream with automatic line flushing

common constructor

PrintWriter(String filename): You can directly write to the file with the given path

PrintWriter(File file): You can directly write to the file represented by File

The above two constructors will automatically complete the stream connection operation internally.

PrintWriter(OutputStream out): Link the PW to the given byte stream (the construction method will complete the conversion stream and other stream connections by itself)

PrintWriter(Writer writer): link PW to other character streams

PrintWriter(OutputStream out, boolean autoflush)

PrintWriter(Writer writer,boolean autoflush)

The above two constructors can pass in the second parameter while linking to the stream. If the value is true, the automatic row refresh function is enabled.

common method

void println(String line): Write out a line of strings by line

features

Automatic line refresh, when this function is turned on, it will be automatically flushed every time a line of string is written using the println method

Java exception handling mechanism:

  • The exception handling mechanism is used to deal with those possible exceptions, but the scenarios that cannot be completely avoided by modifying the logic.
  • And if the exception that can be avoided by modifying the logic is a bug, the exception handling mechanism should not be used to solve it during runtime! It should be corrected in time when coding

The try statement block is used to contain code fragments that may go wrong

catch is used to catch and handle the corresponding exceptions, multiple exceptions can be defined, and multiple exceptions can be combined in one catch.

finally is the last block of the exception, as long as the program executes to try, it must go. It is generally used for operations such as releasing resources.

throw is used to actively throw an exception externally. Either the syntax is satisfied but the business is not satisfied and the exception is actively thrown, or the exception actually occurs but should not be thrown when the current code fragment is resolved. The specific situation should be combined with the actual business analysis.

throws is used to declare that the exception is thrown when the method is declared, so that the caller must handle the exception.

Guess you like

Origin blog.csdn.net/u013488276/article/details/124699806