JavaAPI(2020)

目錄

1. JavaAPI(2020)

  • Object類/Scanner類
  • String類/StringBuffer類/StringBuilder類
  • 數組高級和Arrays類
  • 基本類型包裝類(Integer,Character)
  • 正則表達式(Pattern,Matcher)
  • Math類/Random類/System類
  • BigInteger類/BigDecimal類
  • Date類/DateFromat類/Calendar類
  • LineNumberReader
  • 數據輸入輸出流
  • 內存操作流
  • 打印流
  • 標準輸入輸出流
  • 隨機訪問流
  • 合併流
  • 序列化流和反序列化流
  • Properties

1.1 java.lang.Object

Object類是所有類的根類,所有類都直接或間接的繼承自該類。

1.1.1 成員方法

  • int hashCode(),返回該對象的哈希值。哈希值是對象的邏輯地址值,非物理地址值。
  • Class getClass(),返回Object的運行時類對象,Class是一個類型,是字節碼文件*.class。
  • String toString(),返回對象的文本表現形式,如果沒有重寫由三部分組成,全路徑+@+16進制邏輯內存地址值,System.out.println(此處默認調用.toString)。
  • boolean equals(Object obj),首先判斷地址值是否相同,如果不同則爲false,不同的object重寫後不一樣,但是會挨個比較其中的值,如果值相同,則爲true。
  • protected void finalize(),對象無引用,回收該對象,方法需要重寫。
  • protected void clone(),克隆對象的地址和原地址不同,引用對象的地址和原地址相同。

1.1.2 Demo

package com.xzy.JavaAPI.java.lang.Object;

import java.util.Objects;

public class Student extends Object implements Cloneable {
    private String name;
    private Integer age;


    public Student() {
    }

    public String getName() {
        return name;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
    }

    //Student中默認重寫equals方法
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(name, student.name) &&
                Objects.equals(age, student.age);
    }

    //仿照重寫equals方法
    public boolean equals2(Object o) {
        Student s = (Student) o;
        if (this.name.equals(s.getName()) && this.age == s.getAge()) {
            return true;
        } else {
            return false;
        }
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int hashCode() {
        return super.hashCode();//默認方法
        //  return 10;//重寫方法
    }

    //未重寫toString
    @Override
    public String toString() {
        return super.toString();
    }

    //源碼方法
    //public String toString() {
    //  return getClass().getName() + "@" + Integer.toHexString(hashCode());
    //}
    //仿照源碼重寫toString,作爲普通方法調用
    public String toString2() {
        //Integer類的toHexString方法可以將10進制轉換成16進制並以字符串返回
        String str = Integer.toHexString(this.hashCode());//調用本類this可省略
        return this.getClass().getName() + "@" + str;//調用本類this可省略
    }

    //自定義toString方法
    public String toString3() {
        return name + ":" + age;
    }
}

package com.xzy.JavaAPI.java.lang.Object;

public class ObjectP {
    public static void main(String[] args) throws Throwable {
        //int hashCode()
        Student s1 = new Student();
        Student s2 = new Student();
        int h1 = s1.hashCode();
        int h2 = s2.hashCode();
        System.out.println(h1);
        System.out.println(h2);
        System.out.println("----------1--------");
        //Class getClass()
        Class clazz1 = s1.getClass();
        Class clazz2 = s2.getClass();
        System.out.println(clazz1);
        System.out.println(clazz2);
        String name = clazz1.getName();
        System.out.println(name);
        System.out.println("-----------2-------");
        //String toString()
        String s3 = s1.toString();
        String s4 = s2.toString();
        String s5 = s2.toString2();
        System.out.println(s3);
        System.out.println(s4);
        System.out.println(s5);
        Student joshua = new Student("Joshua", 20);
        System.out.println(joshua.toString3());
        System.out.println("----------3--------");
        //boolean equals(Object obj)
        Student jack = new Student("Jack", 11);
        Student ben = new Student("Ben", 12);
        Student ben2 = new Student("Ben", 12);
        Student mm=jack;
        System.out.println(mm == jack);
        System.out.println(ben == jack);
        System.out.println(ben == ben2);
        //***==在基本數據類型中比較的是值,在引用和對象中比較的是對象的邏輯內存地址
        System.out.println(ben.equals(jack));
        String hello1 = new String("hello");
        String hello2 = new String("hello");
        System.out.println(hello1.equals(hello2));//邏輯內存地址不一樣,堆中的值一樣。String繼承自Object類並重寫了equals方法,先比較內存地址值是否相等,再比較值是否相等。
        System.out.println(hello1==hello2);//比較的是對象的邏輯內存地址值。
        System.out.println(ben2.equals2(ben));
        //void finalize();
        jack.finalize();
        //void clone();
        //一個對象是否能克隆要看該對象是否實現了一個標記接口clonable
        Student student1 = new Student();
        Student student2 = student1;
        //student1和student2是同一個對象,其中student2是student1的引用.
        Object clone = student1.clone();
        Student student3 = (Student) clone;
        System.out.println(student3);
        System.out.println(student1);
    }
}

1.2 java.util.Scanner

1.2.1 構造方法

  • Scanner(InputStream source)構造一個新的 Scanner,它生成的值是從指定的輸入流掃描的。

1.2.2 成員方法

  • String next(),有效字符前面有空格、tab、回車時next()會忽略,next()接收的字符串中不包含空格、tab、回車,next()以回車作爲結束的標誌。
  • String nextLine(),可以接收空格、tab,以回車鍵作爲結束的標誌。

1.2.3 Demo

package com.xzy.JavaAPI.java.util.Scanner;

import java.util.Scanner;

public class ScannerP {
    public static void main(String[] args) {

    }

    private static void partOne() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("please input a number:");
        if (scanner.hasNextInt()) {
            String st = scanner.nextLine();
            System.out.println(st);
        }else {
            System.out.println("error");
        }
        Scanner scanner1 = new Scanner(System.in);
        System.out.println("請輸入任意字符");
        String next = scanner1.next();
        System.out.println(next);
        System.out.println("----------------------");
    }
}

1.3 java.lang.String

1.3.1 構造方法

  • String(byte[] bytes)通過使用平臺的默認字符集解碼指定的 byte 數組,構造一個新的 String。
  • String(byte[] bytes, int offset, int length)通過使用平臺的默認字符集解碼指定的 byte 子數組,構造一個新的 String。
  • String(char[] value)分配一個新的 String,使其表示字符數組參數中當前包含的字符序列。
  • String(char[] value, int offset, int count)分配一個新的 String,它包含取自字符數組參數一個子數組的字符。
  • String(byte[] bytes, Charset charset)通過使用指定的 charset 解碼指定的 byte 數組,構造一個新的 String。

1.3.2 成員方法

  • boolean equals(Object anObject)將此字符串與指定的對象比較。
  • boolean equalsIgnoreCase(String anotherString)將此 String 與另一個 String 比較,不考慮大小寫。
  • boolean contains(CharSequence s)當且僅當此字符串包含指定的 char 值序列時,返回 true。
  • boolean startsWith(String prefix)測試此字符串是否以指定的前綴開始。
  • boolean endsWith(String suffix)測試此字符串是否以指定的後綴結束。
  • boolean isEmpty()當且僅當 length() 爲 0 時返回 true。
  • int length()返回此字符串的長度。
  • char charAt(int index)返回指定索引處的 char 值。
  • int indexOf(int ch)返回指定字符在此字符串中第一次出現處的索引。
  • int indexOf(String str)返回指定子字符串在此字符串中第一次出現處的索引。
  • int indexOf(int ch, int fromIndex)返回在此字符串中第一次出現指定字符處的索引,從指定的索引開始搜索。
  • int indexOf(String str, int fromIndex)返回指定子字符串在此字符串中第一次出現處的索引,從指定的索引開始。
  • String substring(int beginIndex)返回一個新的字符串,它是此字符串的一個子字符串。
  • String substring(int beginIndex, int endIndex)返回一個新字符串,它是此字符串的一個子字符串。
  • byte[] getBytes()使用平臺的默認字符集將此 String 編碼爲 byte 序列,並將結果存儲到一個新的 byte 數組中。
  • char[] toCharArray()將此字符串轉換爲一個新的字符數組。
  • String toLowerCase()使用默認語言環境的規則將此 String 中的所有字符都轉換爲小寫。
  • String toUpperCase()使用默認語言環境的規則將此 String 中的所有字符都轉換爲大寫。
  • String concat(String str)將指定字符串連接到此字符串的結尾。
  • static String valueOf(char[] data)返回 char 數組參數的字符串表示形式。
  • static String valueOf(int i)返回 int 參數的字符串表示形式。
  • static String valueOf(Object obj)返回Object參數的字符串表示形式。
  • String replace(char old,char new)
  • String replace(String old,String new)
  • String trim()
  • int compareTo(String str)
  • int compareToIgnoreCase(String str)
  • byte[] getBytes(String charsetName)使用指定的字符集將此 String 編碼爲 byte 序列,並將結果存儲到一個新的 byte 數組中。

1.3.3 Demo

package com.xzy.JavaAPI.java.lang.String;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Date;
import java.util.Scanner;

import static java.lang.String.valueOf;

public class StringP {
    public static void main(String[] args) {

    }

    private static void part22() {
        String str1 = "中國";
        byte[] bytes1 = str1.getBytes();
        System.out.println(Arrays.toString(bytes1));
        System.out.println(new String(str1));
        String str2="abc";
        byte[] bytes2 = str2.getBytes();
        System.out.println(Arrays.toString(bytes2));
        System.out.println(new String(str2));

        byte[] bys={-28, -72, -83, -27, -101, -67};
        try {
            System.out.println(new String(bys, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try {
            byte[] gbks = "美國".getBytes("gbk");
            System.out.println(new String(gbks, "gbk"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private static void part21() {
        String str1 = "adasdadjavafffffffffosoagknlaskdjlfnblaskdfjava";
        String findStr="java";
        int count = 0;
        int indexOf = str1.indexOf(findStr);
        while (indexOf!=-1) {
            count++;
            int newIndex = indexOf + findStr.length();
            str1=str1.substring(newIndex);
            indexOf= str1.indexOf(findStr);
        }
        System.out.println("字符串出現的次數爲:"+count);
    }

    private static void part20() {
        StringBuilder stringBuilder = new StringBuilder("12345");
        StringBuilder reverse = stringBuilder.reverse();
        System.out.println(reverse.toString());
    }

    private static void part19() {
        String str1 = "abcdefghijklmn12121212AAAAAAAAAAAAAA";
        String substring1 = str1.substring(0, 3);
        System.out.println(substring1);
        String s = substring1.toUpperCase();
        System.out.println(s);
    }

    private static void part18() {
        String str1 = "abcdefghijklmn12121212AAAAAAAAAAAAAA";
        StringBuilder num = new StringBuilder();
        StringBuilder big = new StringBuilder();
        StringBuilder small = new StringBuilder();
        Integer numCount = 0;
        Integer bigCount = 0;
        Integer smallCount = 0;
        char[] chars = str1.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] >= '0' && chars[i] <= '9') {
                num.append(chars[i]);
                numCount++;
            } else if (chars[i] >= 'A' && chars[i] <= 'Z') {
                big.append(chars[i]);
                bigCount++;
            } else if (chars[i] >= 'a' && chars[i] <= 'b') {
                small.append(chars[i]);
                smallCount++;
            }
        }
        System.out.println(num.toString() + "\t出現了" + numCount + "次");
        System.out.println(big.toString() + "\t出現了" + bigCount + "次");
        System.out.println(small.toString() + "\t出現了" + smallCount + "次");

        {
            //清空
            num = null;
            big = null;
            small = null;
            numCount = null;
            bigCount = null;
            smallCount = null;
        }
    }

    private static void part17() {
        String str1 = "abcdefghijklmn";
        char[] chars = str1.toCharArray();
        for (char aChar : chars) {
            System.out.print("[" + aChar + "]" + ",");
        }
        System.out.println();
        for (int i = 0; i < str1.length(); i++) {
            System.out.print("[" + str1.charAt(i) + "]" + ",");
        }
    }

    private static void part16() {
        String username = "admin";
        String password = "admin";
        StringBuilder log = new StringBuilder();
        System.out.println("你只有三次機會輸入用戶名和密碼");
        for (int i = 1; i <= 3; i++) {
            System.out.print("請輸入用戶名:");
            Scanner scanner = new Scanner(System.in);
            String usernameInput = scanner.nextLine();
            log.append(new Date() + "\tusername" + usernameInput + "\n");
            System.out.print("請輸入密碼:");
            String passwordInput = scanner.nextLine();
            log.append(new Date() + "\tpassword:" + passwordInput + "\n");
            if (username.compareTo(usernameInput) == 0 && password.compareTo(passwordInput) == 0) {
                //equals和compareTo好像一樣,歡迎點評
                System.out.println("login success");
                part15();
                System.out.println("系統登錄日誌:\n" + log);
                log = null;//清空
                break;
            } else {
                System.out.println("賬號或者密碼錯誤!" + "剩餘次數" + (3 - i));
            }
        }
    }

    private static void part15() {
        int j = (int) ((Math.random() * 100) + 1);
        int count = 0;
        while (true) {
            count++;
            System.out.println("我已經生成數字[1,100],請輸入一個數字:");
            Scanner scanner = new Scanner(System.in);
            if (scanner.hasNextInt()) {
                int i = scanner.nextInt();
                if (i > j) {
                    System.out.println("你輸入的數字大了");
                } else if (i < j) {
                    System.out.println("你輸入的數字小了");
                } else {
                    System.out.println("猜中了" + i + "," + count + "次");
                    break;
                }
            } else {
                System.out.println("格式不對,請輸入一個int類型的數字!");
            }
        }
    }

    private static void part14() {
        String str1 = "abcde";
        String str2 = "abcde";
        String str3 = "bbcde";
        String str4 = "fghijkl";
        String str5 = "abcdef";
        String str6 = "Abcde";
        Integer integer = Integer.valueOf(str4.charAt(0));
        int compareTo = str1.compareTo(str2);
        System.out.println(compareTo);
        int i = str1.compareTo(str3);
        System.out.println(i);
        int j = str1.compareTo(str4);
        System.out.println(j);
        System.out.println(integer);
        int i1 = str1.compareTo(str5);
        System.out.println(i1);
        int i2 = str6.compareToIgnoreCase(str1);
        System.out.println(i2);
    }

    private static void part13() {
        String str1 = "aaaaaaaaasdadadasdsfnkflsafnkalsdnjakldad";
        String replace = str1.replace('a', 'k');
        String replace1 = str1.replace("da", "II");
        System.out.println(replace);
        System.out.println(replace1);
        String str2 = "   adadaad    dadadad    ";
        String trim = str2.trim();
        System.out.println(trim);
    }

    private static void part12() {
        char[] chars = {'a', 'b', 'c'};
        String s = valueOf(chars);
        String s1 = valueOf(10);
        System.out.println(s);
        System.out.println(s1.charAt(0));
        System.out.println(s1.charAt(1));
        String s2 = valueOf(new Demo());
        System.out.println(s2);
    }

    private static void part11() {
        String str1 = "aaa";
        String str2 = "bbb";
        String concat = str1.concat(str2);//concat只能拼接字符串,如果爲null則空指針異常,加號可以拼接任意類型且一邊爲null不會報空指針異常。
        System.out.println(concat);
    }

    private static void part10() {
        String str1 = "woaixuejava";
        byte[] bytes = str1.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            System.out.print((char) bytes[i]);
        }
        System.out.println("---------------------");
        char[] chars = str1.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            System.out.print(chars[i]);
        }
        System.out.println("---------------------");
        String s = str1.toUpperCase();
        System.out.println(s);
        String s1 = str1.toLowerCase();
        System.out.println(s1);
    }

    private static void part9() {
        String str1 = "abcdefghijklmn";
        String substring1 = str1.substring(str1.indexOf('b'), str1.indexOf('f') + 1);
        System.out.println(substring1);
    }

    private static void part8() {
        String str1 = "abcdefgh";
        String str2 = "cd";
        System.out.println(str1.indexOf(str2));
        int i = str1.indexOf(str2, 3);
        System.out.println(i);
        int a = str1.indexOf('a', 0);
        System.out.println(a);
    }

    private static void part7() {
        String str1 = "abcde";
        String s = valueOf(str1.charAt(1));
        System.out.println(s);
        int a = str1.indexOf('a');
        System.out.println(a);
    }

    private static void part6() {
        String str1 = "abcde";
        String str2 = valueOf(str1.charAt(0));
        String str3 = valueOf(str1.charAt(str1.length() - 1));
        System.out.println(str2);
        System.out.println(str1.startsWith(str2));
        System.out.println(str3);
        System.out.println(str1.endsWith(str3));
        String str4 = "";//str4爲空
        String str5 = null;//str5未指向任何物理邏輯地址,空引用
        System.out.println(str4.isEmpty());
        System.out.println(str5.isEmpty());
        System.out.println("----");
        System.out.println(str4.length());
        System.out.println(str5.length());
    }

    private static void part5() {
        String str1 = "abc";
        String str2 = new String("Abc");
        String str3 = "a";
        System.out.println(str1.equals(str2));
        System.out.println(str1.equalsIgnoreCase(str2));
        System.out.println(str1.contains(str3));
    }

    private static void part4() {
        String str1 = new String("sdadadad");
        String str2 = new String("1111111111111");
        String str3 = str1 + str2;
        System.out.println(str3);
        //1、一個變量字符串加常量之後的結果是變量
        //2、字符串常量的值是不能改變的
        //***變量和誰相加都是變量,兩個常量相加纔是常量
    }

    private static void part3() {
        char[] chars = {'a', 'b', 'c'};
        String s = new String(chars);
        String s1 = new String(chars, 1, 2);
        System.out.println(s);
        System.out.println(s1);
    }

    public static void part2() {
        byte[] bytes = {97, 99, 100};
        String s = new String(bytes);
        String s1 = new String(bytes, 1, 2);
        System.out.println(s1);
        System.out.println(s);
        System.out.println(s.length());
        System.out.println(s1.length());
    }

    private static void part1() {
        String str1 = "abc";//字符串常量,常量放在常量池中的方法區
        String str2 = new String("abc");//堆內存中
        int length = str2.length();
        System.out.println(str2);
        System.out.println(length);
    }
}

1.4 java.lang.StringBuffer

StringBuffer是帶緩衝區的字符串,長度和內容可以改變。
StringBuffer線程是安全的,線程安全的優點是數據安全,缺點是效率低。

1.4.1 構造方法

  • StringBuffer(int capacity)構造一個不帶字符,但具有指定初始容量的字符串緩衝區。
  • StringBuffer(String str)構造一個字符串緩衝區,並將其內容初始化爲指定的字符串內容。
  • StringBuffer()構造一個其中不帶字符的字符串緩衝區,其初始容量爲 16 個字符。

1.4.2 成員方法

  • StringBuffer append(String str)將指定的字符串追加到此字符序列。
  • StringBuffer insert(int offset,String str)將字符串插入此字符序列中。
  • StringBuffer delelteChart(int index)移除此序列指定位置的 char。
  • StringBuffer delete(int start,int end)移除此序列的子字符串中的字符。
  • StringBuffer replace(int start.int end,String str)使用給定 String 中的字符替換此序列的子字符串中的字符。
  • StringBuffer reverse()將此字符序列用其反轉形式取代。
  • String substring(int start)返回一個新的 String,它包含此字符序列當前所包含的字符子序列。
  • String substring(int start,int end)返回一個新的 String,它包含此序列當前所包含的字符子序列。

1.4.3 Demo

package com.xzy.JavaAPI.java.lang.StringBuffer;

public class StringBufferP {
    public static void main(String[] args) {

    }

    private static void part7() {
        StringBuffer hellojava = new StringBuffer("hellojava");
        String substring = hellojava.substring(3);
        System.out.println(hellojava);
        System.out.println(substring);
        String substring1 = hellojava.substring(0, 5);
        System.out.println(substring1);
        System.out.println(hellojava);
    }

    private static void part6() {
        StringBuffer hellojava = new StringBuffer("hellojava");
        hellojava.reverse();
        System.out.println(hellojava);
    }

    private static void part5() {
        StringBuffer hellojava = new StringBuffer("hellojava");
        hellojava.replace(0,5,"hasdasdadhhhh");
        System.out.println(hellojava);
    }

    private static void part4() {
        StringBuffer helloword = new StringBuffer("helloword");
        helloword.deleteCharAt(0);
        helloword.deleteCharAt(3);
        helloword.delete(0,3);//包左不包右
        System.out.println(helloword);
    }

    private static void part3() {
        StringBuffer java = new StringBuffer("java");
        StringBuffer hello = java.insert(0, "hello");
        System.out.println(java);
        System.out.println(hello);
        char[] chars={'a','b','c'};
        java.insert(0,chars,0,1);
        System.out.println(java);
    }

    private static void part2() {
        StringBuffer java = new StringBuffer("java");
        StringBuffer hello = java.append("hello");
        System.out.println(java.capacity());
        System.out.println(hello.capacity());
        System.out.println(java);
        System.out.println(hello);
        System.out.println(java == hello);

        StringBuffer append = java.append(20);
        System.out.println(java);
        System.out.println(append);

        StringBuffer append1 = java.append(true);
        System.out.println(java);
        System.out.println(append1);
    }

    private static void part1() {
        StringBuffer stringBuffer = new StringBuffer();
        int capacity = stringBuffer.capacity();
        System.out.println(capacity);//字符緩衝區容量是緩衝區大小,容量可自動擴容
        System.out.println(stringBuffer.length());//長度是字符緩衝區實際字符的個數
        StringBuffer stringBuffer1 = new StringBuffer(20);
        System.out.println(stringBuffer1.capacity());
        System.out.println(stringBuffer1.length());
        StringBuffer java = new StringBuffer("java");
        System.out.println(java.capacity());
        System.out.println(java.length());//默認容量16+
    }
}

1.5 排序算法

1.5.1 冒泡排序

  • 相鄰元素兩兩比較,大的往後放,小的往前放,第一次完畢,最大值出現在了最大索引處。除最大元素外,剩餘的元素以此類推。

  • 外j內i,for循環0到對象的長度-1、-j-1,循環體爲arr[i]>arr[i+1].if,int temp;temp=arr[i];arr[i]=arr[i+1];arr[i+1]=temp;

    package com.xzy.JavaAPI.Arithmetic;

    public class BinarySearch {
    public static void main(String[] args) {

      }
    
      private static void characterSort() {
          String str1 = "jklmnabcdefghi";
          char[] ch = str1.toCharArray();
          int[] arr=new int[str1.length()];
          for (int i = 0; i < ch.length; i++) {
              arr[i]=(int)ch[i];
          }
    
          for (int j = 1; j < arr.length; j++) {
              for (int i = 0; i < arr.length - 1; i++) {
                  if (arr[i] > arr[j]) {
                      int temp;
                      temp = arr[j];
                      arr[j] = arr[i];
                      arr[i] = temp;
                  }
              }
          }
          for (int i = 0; i < arr.length; i++) {
              ch[i]=(char)arr[i];
          }
          String s = String.valueOf(ch);
          System.out.println("排序後:"+s);
      }
    
      private static void binarySort() {
          int[] arr = getArr();
          int[] num = new int[1];
          if ((int) (Math.random() * 2 + 1) == 1) {
              num[0] = arr[(int) (Math.random() * 9 + 0)];
          } else {
              num[0] = (int) (Math.random() * 1000 + 1);
          }
          System.out.println("我這次要猜的數字是:" + num[0]);
          int min = 0;
          int max = arr.length - 1;
          int mid = (min + max) / 2;
          while (true) {
              if (num[0] >= arr[min] && num[0] <= arr[max]) {
                  if (num[0] > arr[mid]) {
                      min = mid + 1;
                      mid = (min + max) / 2;
                  } else if (num[0] < arr[mid]) {
                      max = mid - 1;
                      mid = (min + max) / 2;
                  } else if (num[0] == arr[mid]) {
                      System.out.println("值找到了,數據的索引是" + mid);
                      break;
                  }
    
              } else {
                  System.out.println("您查找的值不存在");
                  break;
              }
          }
      }
    
      private static int[] getArr() {
          int[] arr = GenerateRandomNumber();
          for (int j = 1; j < arr.length; j++) {
              for (int i = 0; i < arr.length - 1; i++) {
                  if (arr[i] > arr[j]) {
                      int temp;
                      temp = arr[j];
                      arr[j] = arr[i];
                      arr[i] = temp;
                  }
              }
          }
          System.out.println("排序後:");
          for (int i : arr) {
              System.out.print(i + ",");
          }
          System.out.println();
          return arr;
      }
    
      private static int[] GenerateRandomNumber() {
          int[] arr = new int[10];
          for (int i = 0; i < arr.length; i++) {
              arr[i] = (int) (Math.random() * 100 + 1);
              for (int j = 0; j < i; j++) {
                  if (arr[i] == arr[j]) {
                      i--;
                      break;
                  }
              }
          }
          System.out.println("生成的隨機數爲:");
          for (int i : arr) {
              System.out.print(i + ",");
          }
          System.out.println();
          return arr;
      }
    

    }

1.5.2 選擇排序

  • 從最小索引開始,依次選擇每個元素和其他所有的元素進行比較,小的放在小的索引處。

  • 外j內i,外for循環1到對象長度,內for循環0到對象長度-1,循環體爲arr[i]>arr[j].if,int temp;temp=arr[j];arr[j]=arr[i];arr[i]=temp;

    package com.xzy.JavaAPI.Arithmetic;

    public class SelectionSort {
    public static void main(String[] args) {
    int[] arr = GenerateRandomNumber();
    for (int j = 1; j < arr.length; j++) {
    for (int i = 0; i < arr.length-1; i++) {
    if (arr[i]>arr[j]) {
    int temp;
    temp=arr[j];
    arr[j]=arr[i];
    arr[i]=temp;
    }
    }
    }
    System.out.println(“排序後:”);
    for (int i : arr) {
    System.out.print(i+",");
    }

      }
      private static int[] GenerateRandomNumber() {
          int[] arr = new int[10];
          for (int i = 0; i < arr.length; i++) {
              arr[i]= (int) (Math.random() * 100 + 1);
              for (int j = 0; j < i; j++) {
                  if (arr[i]==arr[j]) {
                      i--;
                      break;
                  }
              }
          }
          System.out.println("生成的隨機數爲:");
          for (int i : arr) {
              System.out.print(i+",");
          }
          System.out.println();
          return arr;
      }
    

    }

1.6 查找算法

1.6.1 基本查找

循環遍歷某個值在某個對象中是否存在並返回索引

package com.xzy.JavaAPI.Arithmetic;

public class BasicSearch {
    public static void main(String[] args) {
        int[] arr1 = GenerateASetOfRandomNumbers();
        int[] num = new int[1];
        int[] index = new int[10];
        num[0]=arr1[(int)(Math.random()*10+0)];
        System.out.println("生成一個組中的數據爲:\n"+num[0]);
        for (int i = 0; i < arr1.length; i++) {
            if (arr1[i]==num[0]) {
                index[0]=i;

            }
        }
        System.out.println("已查找到數據,位於原數組的第" + (index[0] + 1) + "個元素");
        System.out.println("查找的數據值爲:"+arr1[index[0]]);

    }

    private static int[] GenerateASetOfRandomNumbers() {
        int[] arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * 100 + 1);
            for (int j = 0; j < i; j++) {
                if (arr[i] == arr[j]) {
                    i--;
                    break;
                }
            }
        }
        System.out.println("生成一組隨機數爲:");
        for (int i : arr) {
            System.out.print(i + ",");
        }
        System.out.println();
        return arr;
    }
}

1.6.2 二分查找

前提是數組是有序的

package com.xzy.JavaAPI.Arithmetic;

public class BinarySearch {
    public static void main(String[] args) {

    }

    private static void characterSort() {
        String str1 = "jklmnabcdefghi";
        char[] ch = str1.toCharArray();
        int[] arr=new int[str1.length()];
        for (int i = 0; i < ch.length; i++) {
            arr[i]=(int)ch[i];
        }

        for (int j = 1; j < arr.length; j++) {
            for (int i = 0; i < arr.length - 1; i++) {
                if (arr[i] > arr[j]) {
                    int temp;
                    temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                }
            }
        }
        for (int i = 0; i < arr.length; i++) {
            ch[i]=(char)arr[i];
        }
        String s = String.valueOf(ch);
        System.out.println("排序後:"+s);
    }

    private static void binarySort() {
        int[] arr = getArr();
        int[] num = new int[1];
        if ((int) (Math.random() * 2 + 1) == 1) {
            num[0] = arr[(int) (Math.random() * 10 + 0)];
        } else {
            num[0] = (int) (Math.random() * 1000 + 1);
        }
        System.out.println("我這次要猜的數字是:" + num[0]);
        int min = 0;
        int max = arr.length - 1;
        int mid = (min + max) / 2;
        while (true) {
            if (num[0] >= arr[min] && num[0] <= arr[max]) {
                if (num[0] > arr[mid]) {
                    min = mid + 1;
                    mid = (min + max) / 2;
                } else if (num[0] < arr[mid]) {
                    max = mid - 1;
                    mid = (min + max) / 2;
                } else if (num[0] == arr[mid]) {
                    System.out.println("值找到了,數據的索引是" + mid);
                    break;
                }

            } else {
                System.out.println("您查找的值不存在");
                break;
            }
        }
    }

    private static int[] getArr() {
        int[] arr = GenerateRandomNumber();
        for (int j = 1; j < arr.length; j++) {
            for (int i = 0; i < arr.length - 1; i++) {
                if (arr[i] > arr[j]) {
                    int temp;
                    temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                }
            }
        }
        System.out.println("排序後:");
        for (int i : arr) {
            System.out.print(i + ",");
        }
        System.out.println();
        return arr;
    }

    private static int[] GenerateRandomNumber() {
        int[] arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * 100 + 1);
            for (int j = 0; j < i; j++) {
                if (arr[i] == arr[j]) {
                    i--;
                    break;
                }
            }
        }
        System.out.println("生成的隨機數爲:");
        for (int i : arr) {
            System.out.print(i + ",");
        }
        System.out.println();
        return arr;
    }
}

1.7 java.util.Arrays

1.7.1 成員方法

  • static int binarySearch(int[] a, int key)使用二分搜索法來搜索指定的 int 型數組,以獲得指定的值。
  • static String toString(short[] a)返回指定數組內容的字符串表示形式。

1.7.2 Demo

package com.xzy.JavaAPI.java.util.Arrays;

import java.util.Arrays;

public class ArraysP {
    public static void main(String[] args) {

    }

    private static void part2() {
        int[] arr = GenerateRandomNumber();
        System.out.println(arr);
        String s = Arrays.toString(arr);
        System.out.println(s);
    }

    private static void part1() {
        int[] arr = GenerateRandomNumber();
        Arrays.sort(arr);
        System.out.println("排序後的數據爲:");
        for (int i : arr) {
            System.out.print(i+",");
        }
        System.out.println();
        int index=arr[(int) (Math.random() * 10 + 0)];
        System.out.println("查找的值爲:"+index);
        int i = Arrays.binarySearch(arr, index);
        System.out.println("查找的索引爲"+i);
    }

    private static int[] GenerateRandomNumber() {
        int[] arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i]= (int) (Math.random() * 100 + 1);
            for (int j = 0; j < i; j++) {
                if (arr[i]==arr[j]) {
                    i--;
                    break;
                }
            }
        }
        System.out.println("生成的隨機數爲:");
        for (int i : arr) {
            System.out.print(i+",");
        }
        System.out.println();
        return arr;
    }
}

1.8 基本數據類型及包裝類型

  • byte,Byte
  • short,Short
  • int,Integer
  • long,Long
  • float,Float
  • double,Double
  • char,Character
  • boolean,Boolean

1.9 java.lang.Integer

1.9.1 構造方法

  • Integer(int value)構造一個新分配的 Integer 對象,它表示指定的 int 值。
  • Integer(String s)構造一個新分配的 Integer 對象,它表示 String 參數所指示的 int 值。

1.9.2 成員方法

  • static String toString(int i, int radix)返回用第二個參數指定基數表示的第一個參數的字符串表示形式。
  • static String toBinaryString(int i)以二進制(基數 2)無符號整數形式返回一個整數參數的字符串表示形式。
  • static String toHexString(int i)以十六進制(基數 16)無符號整數形式返回一個整數參數的字符串表示形式。
  • static String toOctalString(int i)以八進制(基數 8)無符號整數形式返回一個整數參數的字符串表示形式。

1.9.3 Demo

package com.xzy.JavaAPI.java.lang.Integer;



public class IntegerP {
    public static void main(String[] args) {

    }

    private static void part6() {
        //如果int是-128-127之間的話,java會從緩存池中拿,如果不是則會new一個對象new Integer(value)
        Integer integer = new Integer(100);
        Integer i=100;//Integer.valueOf(100)
        i=i+1000;
        System.out.println(integer);
        System.out.println(i);
    }

    private static void part5() {
        //2-36進制有效,0-9+a-z
        int num=100;
        String s = Integer.toString(num, 8);
        System.out.println(s);
        String s1 = Integer.toString(num, 2);
        System.out.println(s1);
        String s2 = Integer.toString(num, 20);
        System.out.println(s2);
        String s3 = Integer.toString(num, 100);
        System.out.println(s3);
        String s4 = Integer.toString(num, 50);
        System.out.println(s4);
        System.out.println("序號\t\t原值\t\t進制數\t\t轉換值");
        for (int i = 0; i < 50; i++) {
            String s5 = Integer.toString(num, i);
            System.out.println(i+"\t\t"+num+"\t\t"+i+"\t\t\t"+s5);
        }
    }

    private static void part4() {
        String s="100";
        Integer integer = new Integer(s);
        int i = integer.intValue();
        System.out.println(i);
        int i1 = Integer.parseInt(s);
        System.out.println(i1);
    }

    private static void part3() {
        //int-->String
        int i=1000;
        String str="";
        str=i+str;
        System.out.println(str);
        Integer integer = new Integer(i);
        System.out.println(integer.toString());
        System.out.println(String.valueOf(i));
        System.out.println(Integer.toString(i));
    }

    private static void part2() {
        Integer integer = new Integer(100);
        System.out.println(integer);
        Integer integer1 = new Integer("1000");
        System.out.println(integer1);
    }

    private static void part1() {
        int i=1231231231;
        int maxValue = Integer.MAX_VALUE;
        int minValue = Integer.MIN_VALUE;
        if (i>=minValue&&i<=maxValue) {
            System.out.println(i+"在int範圍內");
        }else {
            System.out.println(i+"超過int範圍");
        }
        System.out.println("二進制:"+Integer.toBinaryString(i));
        System.out.println("十六進制:"+Integer.toHexString(i));
        System.out.println("十進制:"+Integer.toOctalString(i));
    }
}

1.10 java.lang.Character

1.10.1 構造方法

  • Character(char value)構造一個新分配的 Character 對象,用以表示指定的 char 值。

1.10.2 成員方法

  • static boolean isUpperCase(char ch)確定指定字符是否爲大寫字母。
  • static boolean isLowerCase(char ch)確定指定字符是否爲小寫字母。
  • static boolean isDigit(char ch)確定指定字符是否爲數字。
  • static char toUpperCase(char ch)使用取自 UnicodeData 文件的大小寫映射信息將字符參數轉換爲大寫。
  • static char toLowerCase(char ch)使用取自 UnicodeData 文件的大小寫映射信息將字符參數轉換爲小寫。

1.10.3 Demo

package com.xzy.JavaAPI.java.lang.Character;

public class CharacterP {
    public static void main(String[] args) {

    }

    private static void part3() {
        int big=0;
        int small=0;
        int num=0;
        String s="abcdefABCD1233";
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (Character.isUpperCase(chars[i])) {
                big++;
            }else if(Character.isLowerCase(chars[i])){
                small++;
            }else if(Character.isDigit(chars[i])){
                num++;
            }
        }
        System.out.println("big:" + big);
        System.out.println("small:" + small);
        System.out.println("big:" + num);
    }

    private static void part2() {
        boolean a = Character.isUpperCase('a');
        System.out.println(a);
        boolean b = Character.isLowerCase('b');
        System.out.println(b);
        boolean digit = Character.isDigit('9');
        System.out.println(digit);
        System.out.println(Character.toUpperCase('a'));
        System.out.println(Character.toLowerCase('A'));
    }

    private static void part1() {
        Character ch = new Character('a');
        System.out.println(ch);
        ch='b';//自動裝箱
        System.out.println(ch);
    }
}

1.11 java.lang.Math

1.11.1 成員靜態常量

  • static double E 比任何其他值都更接近 e(即自然對數的底數)的 double 值。
  • static double PI 比任何其他值都更接近 pi(即圓的周長與直徑之比)的 double 值。

1.11.2 靜態成員方法

  • static double abs(double a)返回 double 值的絕對值。
  • static double ceil(double a)返回最小的(最接近負無窮大)double 值,該值大於等於參數,並等於某個整數。
  • static double floor(double a)返回最大的(最接近正無窮大)double 值,該值小於等於參數,並等於某個整數。
  • static float max(float a, float b)返回兩個 float 值中較大的一個。
  • static double pow(double a, double b)返回第一個參數的第二個參數次冪的值。
  • static double random()返回帶正號的 double 值,該值大於等於 0.0 且小於 1.0。
  • static int round(float a)返回最接近參數的 int。
  • static double sqrt(double a)返回正確舍入的 double 值的正平方根。

1.11.3 Demo

package com.xzy.JavaAPI.java.lang.Math;


import java.util.Scanner;

public class MathP {
    public static void main(String[] args) {
        part3();
    }

    private static void part3() {
        System.out.println("請輸入隨機數的起始值:");
        Scanner scanner = new Scanner(System.in);
        int start = scanner.nextInt();
        System.out.println("請輸入隨機數的終止值:");
        int end = scanner.nextInt();
        int[] arr = new int[100];
        System.out.println("序號\t\t數字");
        for (int i = 0; i < 100; i++) {
            arr[i] = (int) (Math.random() * (end - start + 1) + start);//[0,1)*200+100=[0,200)+100=[100,300)
            System.out.println(i + "\t\t" + arr[i]);
        }
    }

    private static void part2() {
        double a = -2.054888887;
        double abs = Math.abs(a);
        System.out.println(abs);
        System.out.println(Math.ceil(2.4879));
        System.out.println(Math.floor(2.4879));
        System.out.println(Math.max(2.5, 3.2));
        System.out.println(Math.pow(2, 3));
        System.out.println((int) (Math.random() * 100 + 1));
        System.out.println(Math.round(3.49));
        System.out.println(Math.sqrt(4));
    }

    private static void part1() {
        double e = Math.E;
        System.out.println(e);
        double pi = Math.PI;
        System.out.println(pi);
    }
}

1.12 java.util.Random

1.12.1 構造方法

  • Random()創建一個新的隨機數生成器。種子是當前時間的毫秒值
  • Random(long seed)使用單個 long 種子創建一個新的隨機數生成器。 使用seed種子生產隨機數

1.12.2 成員方法

  • int nextInt()返回下一個僞隨機數,它是此隨機數生成器的序列中均勻分佈的 int 值。
  • void setSeed(long seed)使用單個 long 種子設置此隨機數生成器的種子。

1.12.3 Demo

package com.xzy.JavaAPI.java.util.Random;

import java.util.Random;
import java.util.Scanner;

public class RandomP {
    public static void main(String[] args) {

    }

    private static void part1() {
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            int i1 = random.nextInt();
            System.out.println(i1);
        }
        System.out.println();
        for (int i = 0; i < 10; i++) {
            System.out.println(random.nextInt());
        }
        for (int i = 0; i < 1000; i++) {
            System.out.print(random.nextInt(100)+1+",");//[0,100)
        }
    }
    private static void part2() {
        Random random = new Random();
        System.out.println("請輸入隨機數的起始值:");
        Scanner scanner = new Scanner(System.in);
        int start = scanner.nextInt();
        System.out.println("請輸入隨機數的終止值:");
        int end = scanner.nextInt();
        int[] arr = new int[100];
        System.out.println("序號\t\t數字");
        for (int i = 0; i < 100; i++) {
            arr[i] = (int) (random.nextInt(end-start+1)+start);//[0,1)*200+100=[0,200)+100=[100,300)
            System.out.println(i + "\t\t" + arr[i]);
        }
    }
}

1.13 java.lang.System

1.13.1 靜態方法

  • static PrintStream err “標準”錯誤輸出流。
  • static InputStream in “標準”輸入流。
  • static PrintStream out “標準”輸出流。

1.13.2 成員方法

  • static void gc()運行垃圾回收器。
    • System.gc()可用於垃圾回收。當使用System.gc()回收某個對象所佔用的內存之前,通過要求程序調用適當的方法來 清理資源。在沒有明確指定資源清理的情況下,
    • Java提高了默認機制來清理該對象的資源,就是調用Object類的finallize()方法。finalize()方法的作用是釋放一個對象佔用的內存空間時,會被JVM調用。
    • 而子類重寫該方法,就可以清理對象佔用的資源,該方法沒有鏈式調用,所以必須手動實現。
    • 從程序的運行結果可以發現,執行System.gc()前,系統會自動調用finallize()方法清除對象佔有的資源,通過super.finalize()方式可以實現從下到上finalize()方法的調用,即先釋放自己的資源,再去釋放父類的資源。
    • 但是,不要在程序中頻繁的調用垃圾回收,因爲每一次執行垃圾回收,jvm都會強制啓動垃圾回收器運行,這會耗費更多的系統資源,會與正常的Java 程序運行爭搶資源,
    • 只有在執行大量的對象的釋放,才能調用垃圾回收最好。
  • static void exit(int status)終止當前正在運行的 Java 虛擬機。
    0正常終止程序,非0非正常終止程序
  • static long currentTimeMillis()返回以毫秒爲單位的當前時間。
  • static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)從指定源數組中複製一個數組,複製從指定的位置開始,到目標數組的指定位置結束。

1.13.3 Demo

package com.xzy.JavaAPI.java.lang.System;

public class Student {
    private String name;
    private Integer age;

    public Student() {
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("父類資源清理");
        super.finalize();
    }
}

package com.xzy.JavaAPI.java.lang.System;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;

public class SystemP {
    public static void main(String[] args) {

    }

    /**
     * @Method {@link SystemP#readLinePra5}
     * @Return {@link Void}
     * @Description 字符緩衝流
     * @Version 1.0
     */
    public static void readLinePra5() {
        InputStream keyboard = System.in;
        BufferedReader br = new BufferedReader(new InputStreamReader(keyboard));
        String s = null;
        try {
            s = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(s);
    }

    public static void readPra4() {
        InputStream keyboard = System.in;
        try {
            int read = keyboard.read();
            System.out.println((char) read);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void part3() {
        System.out.println(System.currentTimeMillis());
        int[] arr1 = {1, 2, 3, 4, 5, 6};
        int[] arr2 = {6, 7, 8, 9, 10};
        System.out.println(Arrays.toString(arr2));
        System.arraycopy(arr1, 2, arr2, 0, 2);
        System.out.println(Arrays.toString(arr2));
    }

    private static void part2() {
        System.out.println("程序將退出");
        System.exit(0);
    }

    private static void part1() {
        Student xzy = new Student("xzy", 20);
        xzy = null;
        System.gc();
    }
}

1.14 java.math.BigInteger

1.14.1 構造方法

  • BigInteger(String val)將BigInteger的十進制字符串表示形式轉換爲BigInteger。

1.14.2 成員方法

  • BigInteger add(BigInteger val)返回其值爲(this + val)的BigInteger。
  • BigInteger subtract(BigInteger val)返回其值爲(this - val)的BigInteger。
  • BigInteger multiply(BigInteger val)返回其值爲(this * val)的BigInteger。
  • BigInteger divide(BigInteger val)返回其值爲(this / val)的BigInteger。
  • BigInteger[] divideAndRemainder(BigInteger val)返回包含(this / val)後跟(this % val)的兩個BigInteger的數組。

1.14.3 Demo

package com.xzy.JavaAPI.java.math.BigInteger;


import java.math.BigInteger;

public class BigIntegerP {
    public static void main(String[] args) {

    }

    private static void part3() {
        BigInteger bigInteger = new BigInteger("10");
        BigInteger bigInteger1 = new BigInteger("20");
        BigInteger add = bigInteger.add(bigInteger1);
        System.out.println(add);
        BigInteger subtract = bigInteger.subtract(bigInteger1);
        System.out.println(subtract);
        BigInteger multiply = bigInteger.multiply(bigInteger1);
        System.out.println(multiply);
        BigInteger divide = bigInteger.divide(bigInteger1);
        System.out.println(divide);
        BigInteger[] bigIntegers = bigInteger.divideAndRemainder(bigInteger1);
        System.out.println("----");
        for (BigInteger integer : bigIntegers) {
            System.out.println(integer);
        }
    }

    private static void part2() {
        BigInteger bigInteger = new BigInteger("214748364812121212");
        System.out.println(bigInteger);
    }

    private static void part1() {
        int maxValue = Integer.MAX_VALUE;
        int minValue = Integer.MIN_VALUE;
        System.out.println(maxValue);//2147483647
        System.out.println(minValue);//-2147483648
        Integer integer = new Integer(maxValue+1);//-2147483648
        //Integer integer1 = new Integer("2147483648");//java.lang.NumberFormatException: For input string: "21474836481
        //System.out.println(integer1);
        System.out.println(integer);
    }
}

1.15 java.math.BigDecimal

1.15.1 靜態方法

  • static int ROUND_CEILING接近正無窮大的舍入模式。 向上取整
  • static int ROUND_FLOOR接近負無窮大的舍入模式。 向下取整
  • static int ROUND_HALF_UP向“最接近的”數字舍入,如果與兩個相鄰數字的距離相等,則爲向上舍入的舍入模式。四捨五入

1.15.2 構造方法

  • BigDecimal(BigInteger val)將BigInteger轉換爲BigDecimal。

1.15.3 成員方法

  • BigDecimal add(BigDecimal augend)返回一個 BigDecimal,其值爲 (this + augend),其標度爲 max(this.scale(), augend.scale())。
  • BigDecimal subtract(BigDecimal subtrahend)返回一個 BigDecimal,其值爲 (this - subtrahend),其標度爲 max(this.scale(), subtrahend.scale())。
  • BigDecimal multiply(BigDecimal multiplicand)返回一個 BigDecimal,其值爲 (this × multiplicand),其標度爲 (this.scale() + multiplicand.scale())。
  • BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)返回一個 BigDecimal,其值爲 (this / divisor),其標度爲指定標度。

1.15.4 Demo

package com.xzy.JavaAPI.java.math.BigDecimal;

import java.math.BigDecimal;

public class BigDecimalP {
    public static void main(String[] args) {
        
    }

    private static void part1() {
        BigDecimal bigDecimal = new BigDecimal("0.999");
        BigDecimal bigDecimal1 = new BigDecimal("1.22355554888");
        BigDecimal add = bigDecimal.add(bigDecimal1);
        System.out.println(add);
        BigDecimal subtract = bigDecimal.subtract(bigDecimal1);
        System.out.println(subtract);
        BigDecimal multiply = bigDecimal.multiply(bigDecimal1);
        System.out.println(multiply);
        BigDecimal divide1 = bigDecimal.divide(new BigDecimal("2"), 3, BigDecimal.ROUND_HALF_UP);
        BigDecimal divide2 = bigDecimal.divide(new BigDecimal("2"), 8, BigDecimal.ROUND_HALF_UP);
        BigDecimal divide3 = bigDecimal.divide(new BigDecimal("2"), 3, BigDecimal.ROUND_CEILING);
        BigDecimal divide4 = bigDecimal.divide(new BigDecimal("2"), 3, BigDecimal.ROUND_FLOOR);
        System.out.println(divide1);
        System.out.println(divide2);
        System.out.println(divide3);
        System.out.println(divide4);
    }
}

1.16 java.util.Date

1.16.1 構造方法

  • Date()分配 Date 對象並初始化此對象,以表示分配它的時間(精確到毫秒)。
  • Date(long date)分配 Date 對象並初始化此對象,以表示自從標準基準時間(稱爲“曆元(epoch)”,即 1970 年 1 月 1 日 00:00:00 GMT)以來的指定毫秒數。

1.16.2 成員方法

  • long getTime()返回自 1970 年 1 月 1 日 00:00:00 GMT 以來此 Date 對象表示的毫秒數。
  • void setTime(long time)設置此 Date 對象,以表示 1970 年 1 月 1 日 00:00:00 GMT 以後 time 毫秒的時間點。

1.16.3 Demo

package com.xzy.JavaAPI.java.util.Date;

import java.util.Date;

public class DateP {
    public static void main(String[] args) {

    }

    private static void part2() {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            System.out.println(i);
        }
        long end = System.currentTimeMillis();
        long time = end - start;
        System.out.println(time);
    }

    private static void part1() {
        Date date = new Date();
        System.out.println(date.toLocaleString());
        Date date1 = new Date(1000);
        System.out.println(date1.toLocaleString());
        System.out.println(date.getTime());
        System.out.println(date1.getTime());
        date.setTime(100000);
        System.out.println(date.toLocaleString());
        long l = System.currentTimeMillis();
        System.out.println(l);
        System.out.println(new Date(l).toLocaleString());
    }
}

1.17 java.text.DateFormat

1.17.1 構造方法

  • protected DateFormat()創建一個新的 DateFormat。

1.17.2 成員方法

  • Date parse(String source)從給定字符串的開始解析文本,以生成一個日期。
  • String format(Date date)將一個 Date 格式化爲日期/時間字符串。

1.17.3 Demo

package com.xzy.JavaAPI.java.text.DateFormat;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtils {
    private DateUtils(){}
    public static String getDate(String str) throws ParseException {
        String pattern="yyyy年MM月dd日HH:mm:ss";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        String parse = simpleDateFormat.parse(str).toLocaleString();
        return parse;
    }
    public static String getDate(String str,String pattern) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        String parse = simpleDateFormat.parse(str).toLocaleString();
        return parse;
    }
    public static String getString(Date date){
        String pattern="yyyy年MM月dd日HH時mm分ss秒";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        String format = simpleDateFormat.format(date);
        return format;
    }
    public static String getString(Date date,String pattern){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        String format = simpleDateFormat.format(date);
        return format;
    }
}

package com.xzy.JavaAPI.java.text.DateFormat;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class DateFormatP {
    public static void main(String[] args) throws ParseException {

    }

    private static void part4() throws ParseException {
        System.out.println("請輸入你的生日:");
        Scanner scanner = new Scanner(System.in);
        String birthday = scanner.nextLine();
        SimpleDateFormat date = new SimpleDateFormat("yyyy年MM月dd日");
        Date parse = date.parse(birthday);
        long time = parse.getTime();
        long currentTimeMillis = System.currentTimeMillis();
        long l = currentTimeMillis - time;
        long i = l / 1000 / 60 / 60 / 24;
        System.out.println(i);
    }

    private static void part3() throws ParseException {
        //工具類調用
        System.out.println(DateUtils.getDate("2020年5月19日20:43:19"));
        System.out.println(DateUtils.getString(new Date()));
        System.out.println("請輸入你的生日:");
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        String birthday = DateUtils.getDate(s, "yyyy年MM月dd日");
        System.out.println(birthday);

    }

    private static void part2() throws ParseException {
        String str="2020年5月19日20:12:20";
        String pattern="yyyy年MM月dd日HH:mm:ss";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        System.out.println(simpleDateFormat.parse(str).toLocaleString());
    }

    private static void part1() {

        String pattern="yyyy年MM月dd日HH時mm分ss秒";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        Date date = new Date();
        String format = simpleDateFormat.format(date);
        System.out.println(format);
    }
}

1.18 java.util.Calendar

1.18.1 構造方法

  • protected Calendar()構造一個帶有默認時區和語言環境的 Calendar。
  • protected Calendar(TimeZone zone, Locale aLocale)構造一個帶有指定時區和語言環境的 Calendar。

1.18.2 成員方法

  • static Calendar getInstance()使用默認時區和語言環境獲得一個日曆。
  • int get(int field)返回給定日曆字段的值。
  • Date getTime()返回一個表示此 Calendar 時間值(從曆元至現在的毫秒偏移量)的 Date 對象。
  • long getTimeInMillis()返回此 Calendar 的時間值,以毫秒爲單位。
  • abstract void add(int field, int amount)根據日曆的規則,爲給定的日曆字段添加或減去指定的時間量。
  • void set(int year, int month, int date)設置日曆字段 YEAR、MONTH 和 DAY_OF_MONTH 的值。

1.18.3 Demo

package com.xzy.JavaAPI.java.util.Calender;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;

public class CalenderP {
    public static void main(String[] args) {

    }

    private static void part4() {
        Calendar in = Calendar.getInstance();
        System.out.println("請輸入一個年份:");
        Scanner scanner = new Scanner(System.in);
        int date = scanner.nextInt();
        in.set(Calendar.YEAR,date);
        in.set(Calendar.MONTH,2);
        in.set(Calendar.DAY_OF_MONTH,1);
        in.add(Calendar.DAY_OF_MONTH,-1);
        int i = in.get(Calendar.DAY_OF_MONTH);
        System.out.println(i);
    }

    private static void part3() {
        Calendar in = Calendar.getInstance();
        in.set(Calendar.YEAR,2010);
        in.add(Calendar.YEAR,5);
        in.add(Calendar.YEAR,-10);
        Date time = in.getTime();
        System.out.println(time.toLocaleString());
    }

    private static void part2() {
        Calendar ca = Calendar.getInstance();
        Date time = ca.getTime();
        System.out.println(time.toLocaleString());
        System.out.println(ca.getTimeInMillis());
    }

    private static void part1() {
        Calendar instance = Calendar.getInstance();
        ArrayList<Integer> in = new ArrayList<>();
        in.add(instance.get(Calendar.YEAR));
        in.add(instance.get(Calendar.MONTH));
        in.add(instance.get(Calendar.DAY_OF_MONTH));
        in.add(instance.get(Calendar.HOUR));
        in.add(instance.get(Calendar.MINUTE));
        in.add(instance.get(Calendar.SECOND));
        in.add(instance.get(Calendar.WEEK_OF_MONTH));
        in.add(instance.get(Calendar.DAY_OF_WEEK));
        for (Integer integer : in) {
            System.out.println(integer);
        }
    }
}

1.19 java.io.File

1.19.1 構造方法

  • File(String pathname)通過將給定路徑名字符串轉換爲抽象路徑名來創建一個新File實例。
  • File(File parent, String child)根據parent抽象路徑名和child路徑名字符串創建一個新File實例。
  • File(String parent, String child)根據parent路徑名字符串和child路徑名字符串創建一個新File實例。

1.19.2 成員方法

  • boolean isDirectory()測試此抽象路徑名錶示的文件是否是一個目錄。
  • boolean isFile()測試此抽象路徑名錶示的文件是否是一個標準文件。
  • boolean exists()測試此抽象路徑名錶示的文件或目錄是否存在。
  • boolean canRead()測試應用程序是否可以讀取此抽象路徑名錶示的文件。
  • boolean canWrite()測試應用程序是否可以修改此抽象路徑名錶示的文件。
  • boolean isHidden()測試此抽象路徑名指定的文件是否是一個隱藏文件。
  • String getAbsolutePath()返回此抽象路徑名的絕對路徑名字符串。
  • String getPath()將此抽象路徑名轉換爲一個路徑名字符串。
  • String getName()返回由此抽象路徑名錶示的文件或目錄的名稱。
  • long length()返回由此抽象路徑名錶示的文件的長度。
  • long lastModified()返回此抽象路徑名錶示的文件最後一次被修改的時間。
  • String[] list()返回一個字符串數組,這些字符串指定此抽象路徑名錶示的目錄中的文件和目錄。
  • File[] listFiles()返回一個抽象路徑名數組,這些路徑名錶示此抽象路徑名錶示的目錄中的文件。

1.19.3 Demo

package com.xzy.JavaAPI.java.io.File;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * File類方法
 */
public class FileP {
    public static void main(String[] args) {

    }

    private static void part11() {
        File a = new File("a");
        File b = new File("b");
        System.out.println(a.mkdir());
        System.out.println(b.mkdir());
        File file = new File("a\\aa.txt");

        try {
            System.out.println(file.createNewFile());
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            System.out.println(file.renameTo(new File("b\\bb.txt")));
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(new File("b\\bb.txt").renameTo(new File("b\\cc.txt")));
        System.out.println(new File("a").renameTo(new File("dd")));
    }

    private static void part10() {
        /**
         * 分析
         * 1.創建測試文件
         * 2.獲取文件夾下文件的父路徑
         * 3.獲取文件夾下文件的名稱
         * 4.對父路徑和文件名稱拼接構成舊file對象,對文件名稱+"1"拼接父路徑構建新的file對象
         * 5.舊.renameto(新)
         *
         */
        try {
            System.out.println(new File("aa\\bb").mkdirs());
            System.out.println(new File("aa\\bb\\a.txt").createNewFile());
            System.out.println(new File("aa\\bb\\b.txt").createNewFile());
            System.out.println(new File("aa\\bb\\c.txt").createNewFile());
            System.out.println("------------創建完成-----------------");
        } catch (IOException e) {
            e.printStackTrace();
        }

        File[] files = new File("aa\\bb").listFiles();
        for (File file : files) {
            if (file.isFile()) {
                String parent = file.getParent();

                String name = file.getName();

                String startName = name.substring(0, 1);

                int endPoint = name.lastIndexOf(".");
                String endName = name.substring(endPoint);

                String newStartName = startName + "k";

                System.out.println(file.renameTo(new File(parent + "\\"+newStartName + endName)));
                System.out.println(new File(parent + "\\" + newStartName + endName));
            }
        }
        try {
            System.out.println(new File("aa\\bb\\ck.txt").delete());
            System.out.println(new File("aa\\bb\\ak.txt").delete());
            System.out.println(new File("aa\\bb\\bk.txt").delete());
            System.out.println(new File("aa\\bb").delete());
            System.out.println(new File("aa").delete());
            System.out.println("------------刪除完成-----------------");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void part9() {
        part8();
        String[] list = new File("aa\\bb").list();
        for (String s : list) {
            System.out.println(s);
        }

        for (String s : list) {
            if (s.endsWith(".txt")) {
                System.out.println(s);
            }
        }

        File[] files = new File("aa\\bb").listFiles();
        for (File file : files) {
            String name = file.getName();
            if (name.endsWith(".txt")) {
                System.out.println(file.getName());
            }
        }
        delete();
    }

    private static void part8() {
        try {
            create();
            System.out.println("=====================================================");
            String[] list = new File("aa\\bb").list();
            for (String s : list) {
                System.out.println(s);
            }
            File[] files = new File("aa\\bb").listFiles();
            for (File file : files) {
                System.out.println(file);
                System.out.println(file.getAbsolutePath());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("------------------------------------");
            delete();
        }
    }

    private static void create() {
        try {
            System.out.println(new File("aa\\bb").mkdirs());
            System.out.println(new File("aa\\bb\\a.txt").createNewFile());
            System.out.println(new File("aa\\bb\\b.txt").createNewFile());
            System.out.println(new File("aa\\bb\\c.txt").createNewFile());
            System.out.println(new File("aa\\bb\\cc").mkdir());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void delete() {
        System.out.println(new File("aa\\bb\\a.txt").delete());
        System.out.println(new File("aa\\bb\\b.txt").delete());
        System.out.println(new File("aa\\bb\\c.txt").delete());
        System.out.println(new File("aa\\bb\\cc").delete());
        System.out.println(new File("aa\\bb").delete());
        System.out.println(new File("aa").delete());
    }

    private static void part7() {
        try {
            System.out.println(new File("a.txt").createNewFile());
            System.out.println(new File("b.txt").createNewFile());
            System.out.println(new File("a.txt").getAbsolutePath());
            System.out.println(new File("src\\main\\java\\com\\xzy\\JavaAPI\\Note\\JavaAPI.md").getAbsolutePath());

            System.out.println(new File("b").getPath());
            long l = new File("b.txt").lastModified();
            Date date = new Date(l);
            System.out.println(date.toLocaleString());
            System.out.println(new File("a.txt").getName());
            System.out.println(new File("b.txt").length());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            new File("a.txt").delete();
            new File("b.txt").delete();
        }
    }

    private static void part6() {
        try {
            File aa = new File("aa");
            File bb = new File("bb");
            File cc = new File("cc.txt");
            System.out.println(aa.mkdir());
            System.out.println(bb.mkdir());
            System.out.println(cc.createNewFile());
            System.out.println("================================");
            System.out.println(aa.isDirectory());
            System.out.println(bb.isFile());
            System.out.println(cc.isFile());
            System.out.println("================================");
            System.out.println(aa.exists());
            System.out.println(bb.exists());
            System.out.println(cc.exists());
            System.out.println("================================");
            System.out.println(aa.canRead());
            System.out.println(bb.canRead());
            System.out.println(cc.canRead());
            System.out.println("================================");
            System.out.println(aa.canWrite());
            System.out.println(bb.canWrite());
            System.out.println(cc.canWrite());
            System.out.println("================================");
            System.out.println(aa.isHidden());
            System.out.println(bb.isHidden());
            System.out.println(cc.isHidden());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void part5() {
        File file = new File("b.txt");
        boolean b = file.renameTo(new File("a.txt"));
        System.out.println(b);
    }

    private static void part4() {
        try {
            File aa = new File("aa");
            boolean newFile1 = aa.createNewFile();

            File file = new File("a.txt");
            boolean newFile = file.createNewFile();

            File aaa = new File("aaa\\bbb");
            File aaa1 = new File("aaa");
            boolean mkdir = aaa.mkdirs();

            System.out.println(newFile1);
            System.out.println(newFile);
            System.out.println(mkdir);

            System.out.println("----------------------------------");
            System.out.println(aa.delete());
            System.out.println(file.delete());
            System.out.println(aaa.delete());
            System.out.println(aaa1.delete());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void part3() {
        try {
            File file = new File("C:\\Users\\xzy\\Desktop\\aa");
            boolean mkdir = file.mkdir();

            File file1 = new File("C:\\Users\\xzy\\Desktop\\bb\\cc");
            boolean mkdir1 = file1.mkdir();
            boolean mkdirs = file1.mkdirs();

            File aaa = new File("aaa");
            boolean mkdir2 = aaa.mkdir();

            System.out.println(mkdir);
            System.out.println(mkdir1);
            System.out.println(mkdirs);
            System.out.println(mkdir2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void part2() {
        try {
            File file = new File("C:\\Users\\xzy\\Desktop\\aa.txt");
            boolean newFile = file.createNewFile();

            File file1 = new File("C:\\Users\\xzy\\Desktop\\test.txt");
            boolean newFile1 = file1.createNewFile();

            File file2 = new File("bb.txt");
            boolean newFile2 = file2.createNewFile();

            File file3 = new File("C:\\Users\\xzy\\Desktop\\test.txt");
            boolean newFile3 = file3.createNewFile();

            System.out.println(newFile);
            System.out.println(newFile1);
            System.out.println(newFile2);
            System.out.println(newFile3);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void part1() {
        File file = new File("C:\\Users\\xzy\\Desktop\\test.txt");
        File file1 = new File("C:\\Users\\xzy\\Desktop", "test.txt");
        File file2 = new File("C:\\Users\\xzy\\Desktop");
        File file3 = new File(file2, "test.txt");
    }
}

1.20 java.io.FileOutputStream

1.20.1 構造方法

  • FileOutputStream(File file)創建一個向指定 File 對象表示的文件中寫入數據的文件輸出流。
  • FileOutputStream(String name)創建一個向具有指定名稱的文件中寫入數據的輸出文件流。
  • FileOutputStream(File file, boolean append)創建一個向指定 File 對象表示的文件中寫入數據的文件輸出流。
  • FileOutputStream(String name, boolean append)創建一個向具有指定 name 的文件中寫入數據的輸出文件流。

1.20.2 成員方法

  • void write(byte[] b)將 b.length 個字節從指定 byte 數組寫入此文件輸出流中。
  • void write(byte[] b, int off, int len)將指定 byte 數組中從偏移量 off 開始的 len 個字節寫入此文件輸出流。
  • void write(int b)將指定字節寫入此文件輸出流。
  • void close()關閉此文件輸出流並釋放與此流有關的所有系統資源。

1.20.3 Demo

package com.xzy.JavaAPI.java.io.FileOutputStream;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class FileOutputStreamP {
    public static void main(String[] args) {

    }

    private static void part5() {
        /**
         * 標準IO寫法
         */
        FileOutputStream fileOutputStream=null;
        try {
            fileOutputStream=new FileOutputStream("b.txt",true);
            fileOutputStream.write("\nxzy".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void part4() {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("b.txt",true);
            fileOutputStream.write("\ntest".getBytes());
            fileOutputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void part3() {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("b.txt",false);
            fileOutputStream.write("test".getBytes());
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void part2() {
        try {

            FileOutputStream fileOutputStream = new FileOutputStream("b.txt");
            String data="hello";
            byte[] bytes = data.getBytes();
            System.out.println(Arrays.toString(bytes));
            fileOutputStream.write(97);
            fileOutputStream.write(98);
            fileOutputStream.write(99);
            fileOutputStream.write(bytes);
            fileOutputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void part1() {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("a.txt");
            String data="hello";
            byte[] bytes = data.getBytes();
            System.out.println(Arrays.toString(bytes));
            fileOutputStream.write(bytes);
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void deleteFiles() {
        System.out.println(new File("a.txt").delete());
        System.out.println(new File("b.txt").delete());
    }
}

1.21 java.io.FileInputStream

1.21.1 構造方法

  • FileInputStream(File file)通過打開一個到實際文件的連接來創建一個 FileInputStream,該文件通過文件系統中的 File 對象 file 指定。
  • FileInputStream(String name)通過打開一個到實際文件的連接來創建一個 FileInputStream,該文件通過文件系統中的路徑名 name 指定。

1.21.2 成員方法

  • int read()從此輸入流中讀取一個數據字節。
  • int read(byte[] b)從此輸入流中將最多 b.length 個字節的數據讀入一個 byte 數組中。
  • int read(byte[] b, int off, int len)從此輸入流中將最多 len 個字節的數據讀入一個 byte 數組中。

1.21.3 Demo

package com.xzy.JavaAPI.java.io.FileInputStream;

import java.io.*;
import java.util.Arrays;

public class FileInputStreamP {
    public static void main(String[] args) {

    }

    private static void part5() {
        //測試
        File file = new File("b.txt");
        System.out.println(file.getAbsolutePath());
        System.out.println(file.getPath());
        System.out.println(file.getParent());
        System.out.println(file.getName());
    }

    private static void part4() {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream("b.txt");
            fileOutputStream = new FileOutputStream("c.txt");
            //自定義字節讀取寫入
            byte[] bys = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bys)) != -1) {
                fileOutputStream.write(bys, 0, len);
            }
            //單字節讀取寫入
            //int data;
            //while ((data = fileInputStream.read()) != -1) {
            //    fileOutputStream.write(data);
            //}
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void part3() {
        /**
         * 讀取自定義字節個數
         */
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("b.txt");
            byte[] bys = new byte[11];
            int len = fileInputStream.read(bys, 0, 11);
            System.out.println(len);
            System.out.println(Arrays.toString(bys));
            System.out.println(new String(bys, 0, 11));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void part2() {
        /**
         * 讀取自定義字節個數
         */
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("b.txt");
            byte[] bys = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bys)) != -1) {
                System.out.print(new String(bys, 0, len));
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void part1() {
        /**
         * 讀取一個字節
         */
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("b.txt");
            int b;
            while (-1 != (b = fileInputStream.read())) {
                System.out.print((char) b);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

1.22 java.io.BufferedInputStream

1.22.1 構造方法

  • BufferedInputStream(InputStream in)創建一個 BufferedInputStream 並保存其參數,即輸入流 in,以便將來使用。

1.22.2 成員方法

  • int read()參見 InputStream 的 read 方法的常規協定。
  • int read(byte[] b, int off, int len)從此字節輸入流中給定偏移量處開始將各字節讀取到指定的 byte 數組中。
  • void reset()參見 InputStream 的 reset 方法的常規協定。

1.22.3 Demo

package com.xzy.JavaAPI.java.io.BufferedInputStream;

import java.io.*;

public class BufferedInputStreamP {
    public static void main(String[] args) {
    }

    private static void part2() {
        BufferedInputStream bis=null;
        BufferedOutputStream bos=null;
        try {
            bis=new BufferedInputStream(new FileInputStream("a.png"));
            bos=new BufferedOutputStream(new FileOutputStream("b.png"));

            byte[] bys = new byte[1024];
            int len;
            while ((len = bis.read(bys)) != -1) {
                bos.write(bys,0,len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void part1() {
        FileInputStream fis = null;
        FileOutputStream fos=null;
        BufferedInputStream bis=null;
        BufferedOutputStream bos=null;
        try {
            fis=new FileInputStream("b.txt");
            fos=new FileOutputStream("c.txt",true);
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            //單字節讀取
//            int data;
//            while ((data = bis.read()) != -1) {
//                bos.write(data);
//            }
            //自定義字節讀取
            byte[] bys = new byte[1024];
            int len;
            while ((len = bis.read(bys)) != -1) {
                bos.write(bys,0,len);
            }
            System.out.println("讀取寫入完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bos.close();
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

1.23 java.io.BufferedOutputStream

1.23.1 構造方法

  • BufferedOutputStream(OutputStream out)創建一個新的緩衝輸出流,以將數據寫入指定的底層輸出流。

1.23.2 成員方法

  • void flush()刷新此緩衝的輸出流。
  • void write(byte[] b, int off, int len)將指定 byte 數組中從偏移量 off 開始的 len 個字節寫入此緩衝的輸出流。
  • void write(int b)將指定的字節寫入此緩衝的輸出流。

1.24 碼錶

  • ASCII:佔1個字節,只用了1個字節中的7位進行編碼,還有一位是符號位,沒有中文編碼,存儲2^7=128位字符
  • Unicode:ASCII的升級,佔用2個字節,Java就是使用的Unicode編碼
  • IOS-8859-1:佔用1個字節,拉丁文編碼,沒有漢字
  • GB2312\GBK\GB18030:2個字節,有中文編碼

1.25 java.io.InputStreamReader

1.25.1 構造方法

  • InputStreamReader(InputStream in, String charsetName)創建使用指定字符集的 InputStreamReader。
  • InputStreamReader(InputStream in)創建一個使用默認字符集的 InputStreamReader。

1.25.2 成員方法

  • int read()讀取單個字符。
  • int read(char[] cbuf, int offset, int length)將字符讀入數組中的某一部分。
  • void close()關閉該流並釋放與之關聯的所有資源。

1.25.3 Demo

package com.xzy.JavaAPI.java.io.InputStreamReader;

import java.io.*;

public class InputStreamReaderP {
    public static void main(String[] args) {
        FileInputStream fis=null;
        FileOutputStream fos=null;
        InputStreamReader isr=null;
        OutputStreamWriter osw=null;
        try {
            fis = new FileInputStream("a.txt");
            fos=new FileOutputStream("b.txt");
            isr = new InputStreamReader(fis);
            osw=new OutputStreamWriter(fos);
            //單字符讀取
//            int data;
//            while ((data = isr.read()) != -1) {
//                System.out.print((char) data);
//            }
            //自定義字符讀取
            char[] cha = new char[1024];
            int len;
            while ((len = isr.read(cha)) != -1) {
                System.out.println(cha);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                osw.close();
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

1.26 java.io.OutputStreamWriter

1.26.1 構造方法

  • OutputStreamWriter(OutputStream out)創建使用默認字符編碼的 OutputStreamWriter。
  • OutputStreamWriter(OutputStream out, String charsetName)創建使用指定字符集的 OutputStreamWriter。

1.26.2 成員方法

  • void close()關閉此流,但要先刷新它。
  • void flush()刷新該流的緩衝。
  • String getEncoding()返回此流使用的字符編碼的名稱。
  • void write(char[] cbuf, int off, int len)寫入字符數組的某一部分。
  • void write(int c)寫入單個字符。
  • void write(String str, int off, int len)寫入字符串的某一部分。

1.27 java.io.BufferedReader

1.27.1 構造方法

  • BufferedReader(Reader in)創建一個使用默認大小輸入緩衝區的緩衝字符輸入流。
  • BufferedReader(Reader in, int sz)創建一個使用指定大小輸入緩衝區的緩衝字符輸入流。

1.27.2 成員方法

  • void close()關閉該流並釋放與之關聯的所有資源。
  • void mark(int readAheadLimit)標記流中的當前位置。
  • boolean markSupported()判斷此流是否支持 mark() 操作(它一定支持)。
  • int read()讀取單個字符。
  • int read(char[] cbuf, int off, int len)將字符讀入數組的某一部分。
  • String readLine()讀取一個文本行。
  • boolean ready()判斷此流是否已準備好被讀取。
  • void reset()將流重置到最新的標記。
  • long skip(long n)跳過字符。

1.27.3 Demo

package com.xzy.JavaAPI.java.io.BufferedReader;

import java.io.*;

public class BufferedReaderP {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;

        FileInputStream fis=null;
        InputStreamReader isr=null;
        BufferedReader bd=null;
        try {
            fos = new FileOutputStream("a.txt");
            osw = new OutputStreamWriter(fos);
            bw = new BufferedWriter(osw);

            fis=new FileInputStream("b.txt");
            isr=new InputStreamReader(fis);
            bd=new BufferedReader(isr);
            //測試
//            for (int i = 0; i < 10; i++) {
//                bw.write("hahahaa"+i);
//                bw.newLine();
//            }
//            bw.flush();
            //每次讀一行
            String str=null;
            while ((str = bd.readLine()) != null) {
                bw.write(str);
                bw.newLine();
            }
            bw.flush();
            //單字符讀取
//            int len;
//            while ((len = bd.read()) != -1) {
//                bw.write(len);
//            }
            //自定義字符讀取
//            char[] chs = new char[1024];
//            int len;
//            while ((len = bd.read(chs)) != -1) {
//                bw.write(chs,0,len);
//            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bw.close();
                bd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

1.28 java.io.BufferedWriter

1.28.1 構造方法

  • BufferedWriter(Writer out)創建一個使用默認大小輸出緩衝區的緩衝字符輸出流。
  • BufferedWriter(Writer out, int sz)創建一個使用給定大小輸出緩衝區的新緩衝字符輸出流。

1.28.2 成員方法

  • void close()關閉此流,但要先刷新它。
  • void flush()刷新該流的緩衝。
  • void newLine()寫入一個行分隔符。
  • void write(char[] cbuf, int off, int len)寫入字符數組的某一部分。
  • void write(int c)寫入單個字符。
  • void write(String s, int off, int len)寫入字符串的某一部分。

1.29 java.io.FileReader

1.29.1 構造方法

  • FileReader(File file)在給定從中讀取數據的 File 的情況下創建一個新 FileReader。
  • FileReader(FileDescriptor fd)在給定從中讀取數據的 FileDescriptor 的情況下創建一個新 FileReader。
  • FileReader(String fileName)在給定從中讀取數據的文件名的情況下創建一個新 FileReader。

1.29.2 成員方法

  • void close()關閉此流,但要先刷新它。
  • void flush()刷新該流的緩衝。
  • void newLine()寫入一個行分隔符。
  • void write(char[] cbuf, int off, int len)寫入字符數組的某一部分。
  • void write(int c)寫入單個字符。
  • void write(String s, int off, int len)寫入字符串的某一部分。

1.29.3 Demo

package com.xzy.JavaAPI.java.io.FileReader;

import java.io.*;

public class FileReaderP {
    public static void main(String[] args) {
        BufferedReader br=null;
        BufferedWriter bw=null;
        try {
            br=new BufferedReader(new FileReader("a.txt"));
            bw=new BufferedWriter(new FileWriter("b.txt"));
              //單字符讀取
//            int len;
//            while ((len = br.read()) != -1) {
//                bw.write(len);
//            }
              //自定義字符讀取
//            char[] chs = new char[1024];
//            int len;
//            while ((len = br.read(chs)) != -1) {
//                bw.write(chs,0,len);
//            }
              //一行一行讀取
            String str=null;
            while ((str = br.readLine()) != null) {
                bw.write(str);
                bw.newLine();
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

1.30 java.io.FileWriter

1.30.1 構造方法

  • FileWriter(File file)根據給定的 File 對象構造一個 FileWriter 對象。
  • FileWriter(File file, boolean append)根據給定的 File 對象構造一個 FileWriter 對象。
  • FileWriter(FileDescriptor fd)構造與某個文件描述符相關聯的 FileWriter 對象。
  • FileWriter(String fileName)根據給定的文件名構造一個 FileWriter 對象。
  • FileWriter(String fileName, boolean append)根據給定的文件名以及指示是否附加寫入數據的 boolean 值來構造 FileWriter 對象。

1.30.2 成員方法

  • void close()關閉此流,但要先刷新它。
  • void flush()刷新該流的緩衝。
  • void newLine()寫入一個行分隔符。
  • void write(char[] cbuf, int off, int len)寫入字符數組的某一部分。
  • void write(int c)寫入單個字符。
  • void write(String s, int off, int len)寫入字符串的某一部分。

1.30.3 Demo

package com.xzy.JavaAPI.java.io.FileWriter;

import java.io.*;
import java.util.ArrayList;
import java.util.Random;

public class FileWriterP {
    public static void main(String[] args) {

    }

    private static void part2() {
        ArrayList<StringBuffer> sb = new ArrayList<>();
        BufferedReader br=null;
        try {
            br=new BufferedReader(new FileReader("a.txt"));

            String st=null;
            while ((st = br.readLine()) != null) {
                sb.add(new StringBuffer(st));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("大轉盤");
        for (int i = 0; i < 10; i++) {
            int x = new Random().nextInt(sb.size());
            System.out.println(sb.get(x));
        }
    }

    private static void part1() {
        ArrayList<StringBuffer> sb = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            sb.add(new StringBuffer(String.valueOf(i)));
        }
        BufferedWriter bw=null;
        try {
            bw=new BufferedWriter(new FileWriter("a.txt"));
            for (StringBuffer sbc : sb) {
                bw.write(new String(sbc));
                if (Integer.valueOf(new String(sbc))<(sb.size()-1)) {
                    bw.flush();
                    bw.newLine();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

1.31 java.io.LineNumberReader

1.31.1 構造方法

  • LineNumberReader(Reader in)使用默認輸入緩衝區的大小創建新的行編號 reader。
  • LineNumberReader(Reader in, int sz)創建新的行編號 reader,將字符讀入給定大小的緩衝區。

1.31.2 成員方法

  • int getLineNumber()獲得當前行號。
  • void mark(int readAheadLimit)標記該流中的當前位置。
  • int read()讀取單個字符。
  • int read(char[] cbuf, int off, int len)將字符讀入數組中的某一部分。
  • String readLine()讀取文本行。
  • void reset()將該流重新設置爲最新的標記。
  • void setLineNumber(int lineNumber)設置當前行號。
  • long skip(long n)跳過字符。

1.31.3 Demo

package com.xzy.JavaAPI.java.io.LineNumberReader;



import java.io.*;

/**
 * @Path com.xzy.JavaAPI.java.io.LineNumberReader.LineNumberReaderP
 * @Description
 * @Author xuzhiyong
 * @DateTime 2020/5/31 1:26
 * @Version 1.0
 * 1.FIXME{@link Void}{@link LineNumberReaderP#getLineNumberP1()}1.0練習getLineNumber方法
 */
public class LineNumberReaderP {
    public static void main(String[] args) {


    }
    /**
     * @Method {@link LineNumberReaderP#getLineNumberP1()}
     * @Return {@link Void}
     * @Description 練習getLineNumber方法
     * @Version 1.0
     */
    public static void getLineNumberP1() {
        BufferedReader br=null;
        LineNumberReader lnr=null;
        BufferedWriter bw=null;

        File f = new File("a\\a-1-test.txt");

        try {
            br = new BufferedReader(new FileReader(f));

            /*//寫入測試數據
            bw=new BufferedWriter(new FileWriter(f));

            for (int i = 0; i < 20; i++) {
                bw.write(String.valueOf(i));
                bw.newLine();
            }
            bw.flush();*/

            lnr = new LineNumberReader(new FileReader(f));

            String str=null;

            //獲取行號new LineNumberReader.getLineNumber
            while ((str = lnr.readLine()) != null) {
                System.out.println(lnr.getLineNumber()+":"+str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                lnr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

1.32 java.io.DataInputStream

1.32.1 構造方法

  • DataInputStream(InputStream in)使用指定的底層 InputStream 創建一個 DataInputStream。

1.32.2 成員方法

  • byte readByte()參見 DataInput 的 readByte 方法的常規協定。

1.32.3 Demo

package com.xzy.JavaAPI.java.io.DataInputStream;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;

import java.io.*;

/**
 * @Path com.xzy.JavaAPI.java.io.DataInputStream.DataInputStreamP
 * @Description DataInputStream應用在網絡編程中
 * @Author xuzhiyong
 * @DateTime 2020/5/31 2:25
 * @Version 1.0
 */
public class DataInputStreamP {

    //日誌記錄
    private static Logger logger=LoggerFactory.getLogger(DataInputStreamP.class);


    public static void main(String[] args) {

        DataInputStream dps=null;

        try {
            FileInputStream fis = new FileInputStream("a\\a-2-test1.txt");
            dps = new DataInputStream(fis);

            //寫和讀順序一致性
            int read = dps.read();
            byte b = dps.readByte();
            System.out.println(read+","+b);

        } catch (FileNotFoundException e) {
            logger.warn("FileNotFoundException",e);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dps != null) {
                try {
                    dps.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

1.33 java.io.DataOutputStream

1.33.1 構造方法

  • DataOutputStream(OutputStream out)創建一個新的數據輸出流,將數據寫入指定基礎輸出流。

1.33.2 成員方法

  • void writeByte(int v)將一個 byte 值以 1-byte 值形式寫出到基礎輸出流中。

1.33.3 Demo

package com.xzy.JavaAPI.java.io.DataOutputStream;

import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Path com.xzy.JavaAPI.java.io.DataOutputStream.DataOutputStreamP
 * @Description DataOutputStream應用在網絡編程中
 * @Author xuzhiyong
 * @DateTime 2020/5/31 2:26
 * @Version 1.0
 */
public class DataOutputStreamP {
    public static void main(String[] args) {
        //引用賦空
        DataOutputStream dps=null;
        //創建數據輸出流對象
        try {
            FileOutputStream fps = new FileOutputStream("a\\a-2-test.txt");
            dps=new DataOutputStream(fps);

            //可以寫入8中基本數據類型和包裝類型,寫和讀順序一致性
            dps.write(100);
            dps.writeByte(20);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                dps.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}  

1.34 java.io.ByteArrayOutputStream

1.34.1 構造方法

  • ByteArrayOutputStream()創建一個新的 byte 數組輸出流。
  • ByteArrayOutputStream(int size)創建一個新的 byte 數組輸出流,它具有指定大小的緩衝區容量(以字節爲單位)。

1.34.2 成員方法

  • void close()關閉 ByteArrayOutputStream 無效。
  • void reset()將此 byte 數組輸出流的 count 字段重置爲零,從而丟棄輸出流中目前已累積的所有輸出。
  • int size()返回緩衝區的當前大小。
  • byte[] toByteArray()創建一個新分配的 byte 數組。
  • String toString()使用平臺默認的字符集,通過解碼字節將緩衝區內容轉換爲字符串。
  • String toString(int hibyte)已過時。 此方法無法將字節正確轉換爲字符。從 JDK 1.1 開始,完成該轉換的首選方法是通過 toString(String enc) 方法(使用一個編碼名稱參數),或 toString() 方法(使用平臺的默認字符編碼)。
  • String toString(String charsetName)用指定的 charsetName,通過解碼字節將緩衝區內容轉換爲字符串。
  • void write(byte[] b, int off, int len)將指定 byte 數組中從偏移量 off 開始的 len 個字節寫入此 byte 數組輸出流。
  • void write(int b)將指定的字節寫入此 byte 數組輸出流。
  • void writeTo(OutputStream out)將此 byte 數組輸出流的全部內容寫入到指定的輸出流參數中,這與使用 out.write(buf, 0, count) 調用該輸出流的 write 方法效果一樣。

1.34.3 Demo

package com.xzy.JavaAPI.java.io.ByteArrayOutputStream;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ByteArrayOutputStreamP {

    //日誌記錄
    private static Logger logger = LoggerFactory.getLogger(ByteArrayOutputStreamP.class);

    public static void main(String[] args) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {
            baos.write("hello".getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        /*byte[] bytes = baos.toByteArray();
        System.out.println(new String(bytes));*/
    }
}

1.35 java.io.ByteArrayInputStream

1.35.1 構造方法

  • ByteArrayInputStream(byte[] buf)創建一個 ByteArrayInputStream,使用 buf 作爲其緩衝區數組。
  • ByteArrayInputStream(byte[] buf, int offset, int length)創建 ByteArrayInputStream,使用 buf 作爲其緩衝區數組。

1.35.2 成員方法

  • int available()返回可從此輸入流讀取(或跳過)的剩餘字節數。
  • void close()關閉 ByteArrayInputStream 無效。
  • void mark(int readAheadLimit)設置流中的當前標記位置。
  • boolean markSupported()測試此 InputStream 是否支持 mark/reset。
  • int read()從此輸入流中讀取下一個數據字節。
  • int read(byte[] b, int off, int len)將最多 len 個數據字節從此輸入流讀入 byte 數組。
  • void reset()將緩衝區的位置重置爲標記位置。
  • long skip(long n)從此輸入流中跳過 n 個輸入字節。

1.36 java.io.CharArrayReader

1.36.1 構造方法

  • CharArrayReader(char[] buf)根據指定的 char 數組創建一個 CharArrayReader。
  • CharArrayReader(char[] buf, int offset, int length)根據指定的 char 數組創建一個 CharArrayReader。

1.36.2 成員方法

  • void close()關閉該流並釋放與之關聯的所有系統資源。
  • void mark(int readAheadLimit)標記流中的當前位置。
  • boolean markSupported()判斷此流是否支持 mark() 操作(它一定支持)。
  • int read()讀取單個字符。
  • int read(char[] b, int off, int len)將字符讀入數組的某一部分。
  • boolean ready()判斷此流是否已準備好被讀取。
  • void reset()將該流重置爲最新的標記,如果從未標記過,則將其重置到開頭。
  • long skip(long n)跳過字符。

1.37 java.io.CharArrayWriter

1.37.1 構造方法

  • CharArrayWriter()創建一個新的 CharArrayWriter。
  • CharArrayWriter(int initialSize)創建一個具有指定初始大小的新 CharArrayWriter。

1.37.2 成員方法

  • CharArrayWriter append(char c)將指定字符添加到此 writer。
  • CharArrayWriter append(CharSequence csq)將指定的字符序列添加到此 writer。
  • CharArrayWriter append(CharSequence csq, int start, int end)將指定字符序列的子序列添加到此 writer。
  • void close()關閉該流。
  • void flush()刷新該流的緩衝。
  • void reset()重置該緩衝區,以便再次使用它而無需丟棄已分配的緩衝區。
  • int size()返回緩衝區的當前大小。
  • char[] toCharArray()返回輸入數據的副本。
  • String toString()將輸入數據轉換爲字符串。
  • void write(char[] c, int off, int len)將字符寫入緩衝區。
  • void write(int c)將一個字符寫入緩衝區。
  • void write(String str, int off, int len)將字符串的某一部分寫入緩衝區。
  • void writeTo(Writer out)將緩衝區的內容寫入另一個字符流。

1.37.3 Demo

package com.xzy.JavaAPI.java.io.CharArrayWriter;

import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.IOException;

/**
 * @Path com.xzy.JavaAPI.java.io.CharArrayWriter.CharArrayWriterP
 * @Description
 * @Author xuzhiyong
 * @DateTime 2020/5/31 23:09
 * @Version 1.0
 */
public class CharArrayWriterP {
    public static void main(String[] args) throws IOException {
        CharArrayWriter caw = new CharArrayWriter();
        char[] arr={'h','e'};
        try {
            caw.write(arr);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            caw.close();
        }

//        char[] data = caw.toCharArray();
        String data = caw.toString();
        System.out.println(data);

        CharArrayReader car = new CharArrayReader(data.toCharArray());

//        int len;
//        while ((len = car.read()) != -1) {
//            System.out.println((char) len);
//        }

        System.out.println(car);


    }
}

1.38 java.io.PrintWriter

1.38.1 構造方法

  • PrintWriter(File file)使用指定文件創建不具有自動行刷新的新 PrintWriter。
  • PrintWriter(File file, String csn)創建具有指定文件和字符集且不帶自動刷行新的新 PrintWriter。
  • PrintWriter(OutputStream out)根據現有的 OutputStream 創建不帶自動行刷新的新 PrintWriter。
  • PrintWriter(OutputStream out, boolean autoFlush)通過現有的 OutputStream 創建新的 PrintWriter。
  • PrintWriter(String fileName)創建具有指定文件名稱且不帶自動行刷新的新 PrintWriter。
  • PrintWriter(String fileName, String csn)創建具有指定文件名稱和字符集且不帶自動行刷新的新 PrintWriter。
  • PrintWriter(Writer out)創建不帶自動行刷新的新 PrintWriter。
  • PrintWriter(Writer out, boolean autoFlush)創建新 PrintWriter。

1.38.2 成員方法

  • void write(String s)寫入字符串。

1.38.3 Demo

package com.xzy.JavaAPI.java.io.PrintWriter;

import java.io.*;

public class PrintWriterP {
    public static void main(String[] args) throws FileNotFoundException {
        PrintWriter pr = null;
        try {
//            pr = new PrintWriter("b.txt");
            //第一種構造方法
//            pr=new PrintWriter(new FileWriter("b.txt"),true);//開啓自動刷新
            //第二種構造方法
            pr = new PrintWriter(new FileOutputStream("b.txt"), true);//開啓自動刷新

            /*{
                注意!JDK8u231自動PrintWriter刷新開啓,但是程序仍然未刷新
            }*/

            pr.print("good");
            pr.print("good");
            pr.print("good");
            pr.print("good");
            System.out.println("----");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//            pr.flush();//刷新或者關閉都會刷新
//            if (pr != null) {
//                pr.close();
        }
    }


}

1.39 java.io.PrintStream

1.39.1 構造方法

  • PrintStream(OutputStream out)創建新的打印流。

1.39.2 成員方法

  • void write(byte[] buf, int off, int len)將 len 字節從指定的初始偏移量爲 off 的 byte 數組寫入此流。

1.39.3 Demo

package com.xzy.JavaAPI.java.io.PrintStream;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;

import java.io.*;

/**
 * @Class PrintStreamP
 * @Description
 * @Author xuzhiyong
 * @DateTime 2020/6/1 17:16
 * @Version 1.0
 */
public class PrintStreamP {

    //日誌記錄
    private static Logger logger = LoggerFactory.getLogger(PrintStreamP.class);

    public static void main(String[] args) {
        FileOutputStream fos = null;
        FileInputStream fis=null;

        try {
            fos = new FileOutputStream("E:\\github\\JavaCodebase\\b\\b-10-test.txt");
            fis = new FileInputStream("E:\\github\\JavaCodebase\\b\\b-9-test.txt");
            PrintStream ps = new PrintStream(fos);

            byte[] bys = new byte[1024];
            int len;
            while ((len = fis.read(bys)) != -1) {
                ps.write(bys,0,len);//字節寫入和讀取保持一致
            }
            ps.flush();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

1.40 java.io.RandomAccessFile

1.40.1 構造方法

  • RandomAccessFile(File file, String mode)創建從中讀取和向其中寫入(可選)的隨機訪問文件流,該文件由 File 參數指定。
  • RandomAccessFile(String name, String mode)創建從中讀取和向其中寫入(可選)的隨機訪問文件流,該文件具有指定名稱。

1.40.2 成員方法

  • int readInt()從此文件讀取一個有符號的 32 位整數。
  • void writeInt(int v)按四個字節將 int 寫入該文件,先寫高字節。
  • FileDescriptor getFD()返回與此流關聯的不透明文件描述符對象。
  • long getFilePointer()返回此文件中的當前偏移量。

1.40.3 Demo

package com.xzy.JavaAPI.java.io.RandomAccessFile;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @Class RandomAccessFileP
 * @Description
 * @Author xuzhiyong
 * @DateTime 2020/6/1 21:28
 * @Version 1.0
 */
public class RandomAccessFileP {

    //日誌記錄
    private static Logger logger = LoggerFactory.getLogger(RandomAccessFileP.class);

    public static void main(String[] args) {

    }

    public static void readAndWriteMethod1() {
        String name = new String("E:\\github\\JavaCodebase\\b\\b-1-test.txt");
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(name, "rw");

//            raf.writeInt(100);//讀寫一致
            System.out.println(raf.readInt());//讀寫一致

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

1.41 java.io.SequenceInputStream

1.41.1 構造方法

  • SequenceInputStream(Enumeration<? extends InputStream> e)通過記住參數來初始化新創建的 SequenceInputStream,該參數必須是生成運行時類型爲 InputStream 對象的 Enumeration 型參數。
  • SequenceInputStream(InputStream s1, InputStream s2)通過記住這兩個參數來初始化新創建的 SequenceInputStream(將按順序讀取這兩個參數,先讀取 s1,然後讀取 s2),以提供從此 SequenceInputStream 讀取的字節。

1.41.2 成員方法

  • int available()返回不受阻塞地從當前底層輸入流讀取(或跳過)的字節數的估計值,方法是通過下一次調用當前底層輸入流的方法。
  • void close()關閉此輸入流並釋放與此流關聯的所有系統資源。
  • int read()從此輸入流中讀取下一個數據字節。
  • int read(byte[] b, int off, int len)將最多 len 個數據字節從此輸入流讀入 byte 數組。

1.41.3 Demo

package com.xzy.JavaAPI.java.io.SequenceInputStream;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;

import java.io.*;
import java.util.Enumeration;
import java.util.Vector;

/**
 * @Class SequenceInputStreamP
 * @Description
 * @Author xuzhiyong
 * @DateTime 2020/6/1 23:23
 * @Version 1.0
 */
public class SequenceInputStreamP {

    //日誌記錄
    private static Logger logger = LoggerFactory.getLogger(SequenceInputStreamP.class);

    public static void main(String[] args) {

    }

    public static void constructionMethod2() {
        String in1 = new String("E:\\github\\JavaCodebase\\b\\b-2-test.txt");
        String in2 = new String("E:\\github\\JavaCodebase\\b\\b-3-test.txt");
        String in3 = new String("E:\\github\\JavaCodebase\\b\\b-5-test.txt");

        FileInputStream fis1 =null;
        FileInputStream fis2 =null;
        FileInputStream fis3 =null;

        Vector<InputStream> is = new Vector<>();

        try {
            fis1 = new FileInputStream(in1);
            fis2 = new FileInputStream(in2);
            fis3 = new FileInputStream(in3);
            is.add(fis1);
            is.add(fis2);
            is.add(fis3);
            Enumeration<InputStream> ele = is.elements();

            FileOutputStream fos = new FileOutputStream("E:\\github\\JavaCodebase\\b\\b-4-test.txt");

            SequenceInputStream sis = new SequenceInputStream(ele);

            /*byte[] bys = new byte[1024];
            int len;
            while ((len = sis.read(bys)) != -1) {
                fos.write(bys,0,len);
            }*/
            int len;
            while ((len = sis.read()) != -1) {
                fos.write(len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis1 != null) {
                try {
                    fis1.close();
                    fis2.close();
                    fis3.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void constructionMethod1() {
        String in1 = new String("E:\\github\\JavaCodebase\\b\\b-2-test.txt");
        String in2 = new String("E:\\github\\JavaCodebase\\b\\b-3-test.txt");

        FileInputStream fis1 =null;
        FileInputStream fis2 =null;

        try {
            fis1 = new FileInputStream(in1);
            fis2 = new FileInputStream(in2);

            FileOutputStream fos = new FileOutputStream("E:\\github\\JavaCodebase\\b\\b-4-test.txt");

            SequenceInputStream sis = new SequenceInputStream(fis1,fis2);

            /*byte[] bys = new byte[1024];
            int len;
            while ((len = sis.read(bys)) != -1) {
                fos.write(bys,0,len);
            }*/
            int len;
            while ((len = sis.read()) != -1) {
                fos.write(len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis1 != null) {
                try {
                    fis1.close();
                    fis2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

1.42 java.io.ObjectOutputStream

1.42.1 構造方法

  • protected ObjectOutputStream()爲完全重新實現 ObjectOutputStream 的子類提供一種方法,讓它不必分配僅由 ObjectOutputStream 的實現使用的私有數據。
  • ObjectOutputStream(OutputStream out)創建寫入指定 OutputStream 的 ObjectOutputStream。

1.42.2 成員方法

  • void writeObject(Object obj)將指定的對象寫入 ObjectOutputStream。

1.42.3 Demo

package com.xzy.JavaAPI.java.io.ObjectOutputStream;


import java.io.Serializable;

/**
 * @Class Student
 * @Description 序列化版本ID
 *              序列化非持久關鍵字transient,不允許序列化到硬盤上
 * @Author xuzhiyong
 * @DateTime 2020/6/2 3:14
 * @Version 1.0
 */
public class Student implements Serializable {

    private static final long serialVersionUID = -5005869420439727374L;//序列化版本ID
    private transient String name;//序列化非持久關鍵字transient,不允許序列化到硬盤上
    private Integer age;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Student() {
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

package com.xzy.JavaAPI.java.io.ObjectOutputStream;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;

import java.io.*;

/**
 * @Class ObjectOutputStreamP
 * @Description 序列化和反序列化,序列化對象需要實現Serializable接口,反序列化的包名和序列化時應一致。
 *
 * @Author xuzhiyong
 * @DateTime 2020/6/2 2:39
 * @Version 1.0
 */
public class ObjectOutputStreamP {

    //日誌記錄
    private static Logger logger = LoggerFactory.getLogger(ObjectOutputStreamP.class);

    public static void main(String[] args) {

    }

    public static void constructionMethodAndreadObjectMethod2() {
        FileInputStream fis =null;
        ObjectInputStream ois =null;
        try {
            fis = new FileInputStream("Student.txt");
            ois = new ObjectInputStream(fis);

            Student stu = (Student) ois.readObject();
            System.out.println(stu.getName() + stu.getAge());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void constructionMethodAndWriteObjectMethod1() {
        Student stu1 = new Student("xzy", 20);
        FileOutputStream fs =null;
        try {
            fs = new FileOutputStream("Student.txt");
            ObjectOutputStream oos = new ObjectOutputStream(fs);

            oos.writeObject(stu1);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fs != null) {
                try {
                    fs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

1.43 java.io.ObjectInputStream

1.43.1 構造方法

  • protected ObjectInputStream()爲完全重新實現 ObjectInputStream 的子類提供一種方式,讓它不必分配僅由 ObjectInputStream 的實現使用的私有數據。
  • ObjectInputStream(InputStream in)創建從指定 InputStream 讀取的 ObjectInputStream。

1.43.2 成員方法

  • Object readObject()從 ObjectInputStream 讀取對象。

1.44 java.util.Properties

1.44.1 構造方法

  • Properties()創建一個無默認值的空屬性列表。
  • Properties(Properties defaults)創建一個帶有指定默認值的空屬性列表。

1.44.2 成員方法

  • Set keySet()獲得key集合
  • Set<Map.entry<Object,Object>> entrySet()獲得key+value
  • Enumeration elements獲得value集合
  • Object put(Object,Object)添加數據
  • Object setProperty(String,String)
  • Set stringPropertyNames返回key,前提是使用setProperty添加數據
  • String getProperty(String)返回value
  • void store(FileWriter,String)將數據寫入到FileWriter指向的文件
  • void load(FileReader)將指向文件中數據加載進集合

1.44.3 Demo

package com.xzy.JavaAPI.java.util.Properties;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import jdk.nashorn.internal.parser.JSONParser;
import jdk.nashorn.internal.runtime.JSONFunctions;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @Class PropertiesP
 * @Description
 * @Author xuzhiyong
 * @DateTime 2020/6/2 3:40
 * @Version 1.0
 */
public class PropertiesP {

    //日誌記錄
    private static Logger logger = LoggerFactory.getLogger(PropertiesP.class);

    public static void main(String[] args) {
    }

    public static void method3() {
        Properties pr = new Properties();
        String str = new String("E:\\github\\JavaCodebase\\b\\b-2-test.txt");
        System.out.println("------------------------------------");
        FileReader fr=null;

        try {
            fr=new FileReader(str);
            pr.load(fr);
            Set<Object> keys = pr.keySet();//不太完美,是否可以使用本地工具類轉換成Set<String>

            for (Object key : keys) {
                String value = (String) pr.get(key);
                System.out.println(key + "::" + value);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void method2() {
        Properties pr = new Properties();
        pr.put("xzy","101");//pr.put("xzy",101)運行報錯,爲何?
        pr.put("Tom","102");
        pr.put("Tom","103");

        String str = new String("E:\\github\\JavaCodebase\\b\\b-2-test.txt");
        FileWriter fw =null;

        try {
            fw = new FileWriter(str);
            pr.store(fw,"hello");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void method1() {
        Properties pr = new Properties();
        pr.put("xzy","20");
        System.out.println(pr);
        //遍歷key
        Set<Object> ob = pr.keySet();
        for (Object key : ob) {
            Object value = pr.get(key);
            System.out.println(key + ":" + value);
        }
        //遍歷key+value
        Set<Map.Entry<Object, Object>> en = pr.entrySet();
        for (Map.Entry<Object, Object> ent : en) {
            System.out.println(ent.getKey() + ":" + ent.getValue());

        }
        //遍歷所有的value
        Enumeration<Object> el = pr.elements();
        while (el.hasMoreElements()) {
            Object value = el.nextElement();
            System.out.println(value);
        }

        System.out.println("-------------------------------------");
        pr.setProperty("yy","100");//參數先定位String

        //獲得key集合
        Set<String> keys = pr.stringPropertyNames();
        System.out.println(keys);
        for (String key : keys) {
            String value = pr.getProperty(key);
            System.out.println(key + "::" + value);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章