ArrayList与HashMap的嵌套使用

  1. /*
  2. ArrayList与HashMap的嵌套使用
  3. */
  4. public static void main(String[] args) {
  5. ArrayList<HashMap<String,String>> array = new ArrayList<>();
  6. HashMap<String,String> hm1 = new HashMap<>();
  7. hm1.put("孙策","大乔");
  8. hm1.put("周瑜","小乔");
  9. array.add(hm1);
  10. HashMap<String,String> hm2 = new HashMap<>();
  11. hm1.put("孙策1","大乔1");
  12. hm1.put("周瑜1","小乔1");
  13. array.add(hm2);
  14. HashMap<String,String> hm3 = new HashMap<>();
  15. hm1.put("孙策2","大乔2");
  16. hm1.put("周瑜2","小乔2");
  17. array.add(hm3);
  18. for (HashMap<String,String> hm:array){
  19. for (String key:hm.keySet()){
  20. System.out.println(key+","+hm.get(key));
  21. }
  22. }
  23. }

孙策2,大乔2 孙策1,大乔1 周瑜2,小乔2 孙策,大乔 周瑜1,小乔1 周瑜,小乔

Process finished with exit code 0

  1. /*
  2. ArrayList与HashMap的嵌套使用
  3. */
  4. public static void main(String[] args) {
  5. HashMap<String,ArrayList<String>> hm = new HashMap<>();
  6. ArrayList<String> array1 = new ArrayList<>();
  7. array1.add("诸葛");
  8. array1.add("刘备");
  9. hm.put("三国",array1);
  10. ArrayList<String> array2 = new ArrayList<>();
  11. array2.add("八戒");
  12. array2.add("悟空");
  13. hm.put("西游",array2);
  14. ArrayList<String> array3 = new ArrayList<>();
  15. array3.add("宋飞");
  16. array3.add("武松");
  17. hm.put("水浒",array3);
  18. for (String s:hm.keySet()){
  19. System.out.print(s+":");
  20. for (String array:hm.get(s)){
  21. System.out.print(array+"、");
  22. }
  23. System.out.println("\n");
  24. }
  25. }

水浒:宋飞、武松、

西游:八戒、悟空、

三国:诸葛、刘备、

Process finished with exit code 0

统计字符出现次数

hashmap 键值应为包装类
使用TreeMap可使结果有序

  1. /*
  2. 统计字符串中各个字母出现的次数
  3. */
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6. System.out.print("请输入字符串:");
  7. String line = sc.nextLine();
  8. TreeMap<Character, Integer> hm = new TreeMap<>();
  9. for (int i = 0; i < line.length(); i++) {
  10. char key = line.charAt(i);
  11. Integer value = hm.get(key);
  12. //先判断键 是否存在
  13. if (value == null){
  14. hm.put(key,1);
  15. }else{
  16. value++;
  17. hm.put(key,value);
  18. }
  19. }
  20. StringBuffer sb = new StringBuffer();
  21. Set<Character> keySet = hm.keySet();
  22. for (Character key:keySet){
  23. Integer value = hm.get(key);
  24. sb.append(key).append("("+value+")");
  25. }
  26. String res = sb.toString();
  27. System.out.println(res);
  28. }

请输入字符串:bdacegf a(1)b(1)c(1)d(1)e(1)f(1)g(1)

Process finished with exit code 0

Collections 类

对集合操作的工具类
image.png

  1. public static void main(String[] args) {
  2. List<Integer> list = new ArrayList<>();
  3. list.add(30);
  4. list.add(10);
  5. list.add(40);
  6. list.add(50);
  7. list.add(20);
  8. //排序
  9. Collections.sort(list);
  10. System.out.println(list);
  11. //[10, 20, 30, 40, 50]
  12. //反转
  13. Collections.reverse(list);
  14. System.out.println(list);
  15. //[50, 40, 30, 20, 10]
  16. //随机排序
  17. Collections.shuffle(list);
  18. System.out.println(list);
  19. //[20, 40, 50, 30, 10]
  20. }

排序

  1. public class Teacher {
  2. private String name;
  3. private int age;
  4. public Teacher() {
  5. }
  6. public Teacher(String name, int age) {
  7. this.name = name;
  8. this.age = age;
  9. }
  10. @Override
  11. public String toString() {
  12. return "Teacher{" +
  13. "name='" + name + '\'' +
  14. ", age=" + age +
  15. '}';
  16. }
  17. @Override
  18. public boolean equals(Object o) {
  19. if (this == o) return true;
  20. if (o == null || getClass() != o.getClass()) return false;
  21. Teacher teacher = (Teacher) o;
  22. if (age != teacher.age) return false;
  23. return name != null ? name.equals(teacher.name) : teacher.name == null;
  24. }
  25. @Override
  26. public int hashCode() {
  27. int result = name != null ? name.hashCode() : 0;
  28. result = 31 * result + age;
  29. return result;
  30. }
  31. public String getName() {
  32. return name;
  33. }
  34. public void setName(String name) {
  35. this.name = name;
  36. }
  37. public int getAge() {
  38. return age;
  39. }
  40. public void setAge(int age) {
  41. this.age = age;
  42. }
  43. }

创建匿名内部类排序

  1. public static void main(String[] args) {
  2. ArrayList<Teacher> ts = new ArrayList<>();
  3. Teacher s1 = new Teacher("张三", 40);
  4. Teacher s2 = new Teacher("李四", 30);
  5. Teacher s3 = new Teacher("王五", 10);
  6. Teacher s4 = new Teacher("李四", 20);
  7. //Teacher s5 = new Teacher("m四", 20);
  8. ts.add(s1);
  9. ts.add(s2);
  10. ts.add(s3);
  11. ts.add(s4);
  12. //set.add(s5);
  13. //创建匿名内部类排序
  14. Collections.sort(ts, new Comparator<Teacher>() {
  15. @Override
  16. public int compare(Teacher s1, Teacher s2) {
  17. int num = s1.getAge() - s2.getAge(); //age升序
  18. //如年龄相同,比较名字
  19. int num2 = num == 0?s1.getName().compareTo(s2.getName()):num;
  20. return num2;
  21. }
  22. });
  23. for (Teacher t:ts){
  24. System.out.println(t.getName()+","+t.getAge());
  25. }
  26. }

模拟斗地主

  1. /*
  2. 模拟斗地主
  3. */
  4. public static void main(String[] args) {
  5. //定义花色
  6. String[] colors = {"♥","♠","♦","♣"};
  7. String[] numbers = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
  8. ArrayList<String> array = new ArrayList<>();
  9. for (String color:colors){
  10. for (String number:numbers){
  11. array.add(color+number);
  12. }
  13. }
  14. array.add("大王");
  15. array.add("小王");
  16. //洗牌
  17. Collections.shuffle(array);
  18. //System.out.println(array);
  19. //发牌
  20. ArrayList<String> player1 = new ArrayList<>();
  21. ArrayList<String> player2 = new ArrayList<>();
  22. ArrayList<String> player3 = new ArrayList<>();
  23. ArrayList<String> less = new ArrayList<>();
  24. for (int i = 0;i<array.size();i++){
  25. String poker = array.get(i);
  26. if (i>=array.size()-3){
  27. less.add(poker);
  28. }else if (i%3==0){
  29. player1.add(poker);
  30. }else if (i%3==1){
  31. player2.add(poker);
  32. }else if (i%3==2){
  33. player3.add(poker);
  34. }
  35. }
  36. showPoker("张三",player1);
  37. showPoker("李四",player2);
  38. showPoker("王五",player3);
  39. showPoker("底牌",less);
  40. }
  41. public static void showPoker(String name,ArrayList<String> array){
  42. System.out.print(name+":");
  43. for (String s:array){
  44. System.out.print(s+" ");
  45. }
  46. System.out.println();
  47. }

张三:♦A ♠5 ♣7 ♣K ♣3 ♣9 ♦Q ♣2 小王 ♦K ♠3 ♦6 ♦8 ♥5 ♦10 ♠7 ♦4 李四:♠2 ♥A ♥8 ♥10 ♣A ♥6 ♣6 ♣J ♥Q ♠8 ♠J ♠9 ♥2 ♠Q ♥7 ♣8 ♠A 王五:♥3 ♣4 ♣10 ♥9 ♦5 ♠10 ♥4 ♦9 ♥K ♠4 ♠6 ♣Q ♥J ♦7 大王 ♠K ♦2 底牌:♣5 ♦J ♦3

对扑克排序

  1. public class Demo {
  2. /*
  3. 模拟斗地主
  4. */
  5. public static void main(String[] args) {
  6. //定义花色
  7. String[] colors = {"♥", "♠", "♦", "♣"};
  8. String[] numbers = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
  9. //对扑克按序 排列
  10. //根据序列获取对应扑克
  11. HashMap<Integer, String> hm = new HashMap<>();
  12. ArrayList<Integer> array = new ArrayList<>();
  13. int index = 1;
  14. for (String number : numbers) {
  15. for (String color : colors) {
  16. array.add(index);
  17. hm.put(index++, color + number);
  18. }
  19. }
  20. array.add(index);
  21. hm.put(index++, "♚"); //小王
  22. array.add(index);
  23. hm.put(index++, "♕"); //大王
  24. System.out.println(array); //序列
  25. /*
  26. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  27. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
  28. 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  29. 52, 53, 54]
  30. */
  31. System.out.println(hm); //扑克
  32. /*
  33. {1=♥2, 2=♠2, 3=♦2, 4=♣2, 5=♥3, 6=♠3, 7=♦3, 8=♣3, 9=♥4, 10=♠4,
  34. 11=♦4, 12=♣4, 13=♥5, 14=♠5, 15=♦5, 16=♣5, 17=♥6, 18=♠6, 19=♦6, 20=♣6,
  35. 21=♥7, 22=♠7, 23=♦7, 24=♣7, 25=♥8, 26=♠8, 27=♦8, 28=♣8, 29=♥9, 30=♠9,
  36. 31=♦9, 32=♣9, 33=♥10, 34=♠10, 35=♦10, 36=♣10, 37=♥J, 38=♠J, 39=♦J, 40=♣J,
  37. 41=♥Q, 42=♠Q, 43=♦Q, 44=♣Q, 45=♥K, 46=♠K, 47=♦K, 48=♣K, 49=♥A, 50=♠A,
  38. 51=♦A, 52=♣A, 53=小王, 54=大王}
  39. */
  40. //洗牌 -->打乱序号
  41. Collections.shuffle(array);
  42. //System.out.println(array);
  43. //发牌 使用TreeSet集合存储序列,使之有序
  44. TreeSet<Integer> player1 = new TreeSet<>();
  45. TreeSet<Integer> player2 = new TreeSet<>();
  46. TreeSet<Integer> player3 = new TreeSet<>();
  47. TreeSet<Integer> less = new TreeSet<>();
  48. //发牌 -->实际分发的是序号,最后根据序号,得到属于自己的牌
  49. for (int i = 0;i<array.size();i++){
  50. Integer poker = array.get(i);
  51. if (i>=array.size()-3){
  52. less.add(poker);
  53. }else if (i%3==0){
  54. player1.add(poker);
  55. }else if (i%3==1){
  56. player2.add(poker);
  57. }else if (i%3==2){
  58. player3.add(poker);
  59. }
  60. }
  61. showPoker("张三",player1,hm);
  62. showPoker("李四",player2,hm);
  63. showPoker("王五",player3,hm);
  64. showPoker("底牌",less,hm);
  65. }
  66. public static void showPoker(String name, TreeSet<Integer> array,HashMap<Integer,String> hm) {
  67. System.out.print(name + ":");
  68. for (Integer key : array) {
  69. System.out.print(hm.get(key)+" ");
  70. }
  71. System.out.println(); //换行
  72. }
  73. }

张三:♣2 ♠3 ♦3 ♣3 ♥4 ♥5 ♠6 ♥7 ♥8 ♠8 ♣8 ♥9 ♣9 ♥10 ♠J ♣K ♦A 李四:♦2 ♥3 ♠4 ♦5 ♦7 ♠10 ♦10 ♣J ♥Q ♠Q ♦Q ♥K ♠K ♦K ♠A ♣A ♕ 王五:♥2 ♠2 ♦4 ♣4 ♠5 ♣5 ♥6 ♦6 ♣6 ♠7 ♣7 ♦8 ♠9 ♦9 ♣Q ♥A ♚ 底牌:♣10 ♥J ♦J

File类

image.png

构造方法

  1. /*
  2. File类
  3. */
  4. public static void main(String[] args) {
  5. File f1 = new File("D:\\Java\\test.txt");
  6. System.out.println(f1); //D:\Java\test.txt
  7. File f2 = new File("D:\\Java","test.txt");
  8. System.out.println(f2); //D:\Java\test.txt
  9. File f3 = new File("D:\\Java");
  10. File f4 = new File(f3,"test.txt");
  11. System.out.println(f4); //D:\Java\test.txt
  12. }

创建文件或文件夹

  1. public static void main(String[] args) throws IOException {
  2. File f1 = new File("D:\\Java\\test.txt");
  3. /*
  4. 抛出异常 throws IOException
  5. 如文件不存在,则创建文件,返回true
  6. 文件已存在则返回false
  7. */
  8. //System.out.println(f1.createNewFile());
  9. File f2 = new File("D:\\Java\\test");
  10. /*
  11. 创建文件夹,不存在-->创建返回true
  12. 存在-->false
  13. */
  14. //System.out.println(f2.mkdir());
  15. File f3 = new File("D:\\Java\\test1\\test");
  16. /*
  17. 创建多级文件夹,不存在-->创建返回true
  18. 存在-->false
  19. */
  20. //System.out.println(f3.mkdirs());
  21. }

image.png

常用方法

  1. /*
  2. File类
  3. */
  4. public static void main(String[] args) throws IOException {
  5. File f1 = new File("D:\\Java\\javaFound");
  6. //是否为目录
  7. System.out.println(f1.isDirectory());
  8. //是否为文件
  9. System.out.println(f1.isFile());
  10. //是否存在
  11. System.out.println(f1.exists());
  12. //获取绝对路径
  13. System.out.println(f1.getAbsolutePath());
  14. //获取相对路径
  15. System.out.println(f1.getPath());
  16. //获取文件(夹)名
  17. System.out.println(f1.getName());
  18. File f = new File("D:\\Java");
  19. //获取目录下文件列表
  20. String[] str = f.list();
  21. for (String s:str){
  22. System.out.println(s);
  23. }
  24. System.out.println("-------------");
  25. File[] files = f.listFiles();
  26. for (File file:files){
  27. if (file.isFile()){ //是否为文件
  28. System.out.println(file); //路径
  29. System.out.println(file.getName()); //文件名
  30. }
  31. }
  32. }

true false true D:\Java\javaFound D:\Java\javaFound javaFound 09《Spring Boot企业级开发教材》 12《Java EE企业级应用开发Spring+Sspring MVC+MyBatis》 Java.md javaFound Java笔记.md SpringBoot SpringBoot.md SQL.md

毕业设计.md

D:\Java\Java.md Java.md D:\Java\Java笔记.md Java笔记.md D:\Java\SpringBoot.md SpringBoot.md D:\Java\SQL.md SQL.md D:\Java\毕业设计.md 毕业设计.md

Process finished with exit code 0

  1. public static void main(String[] args) throws IOException {
  2. File file = new File("test.txt");
  3. //相对路径创建文件
  4. //System.out.println(file.createNewFile());
  5. //删除文件
  6. System.out.println(file.delete());
  7. File file1 = new File("src\\content");
  8. //创建目录(文件夹)
  9. System.out.println(file1.mkdir());
  10. //删除目录
  11. System.out.println(file1.delete());
  12. //如目录下含有文件,则不能直接删除
  13. }

递归

  1. public static void main(String[] args) throws IOException {
  2. System.out.println(rabbit(20)); //6765
  3. System.out.println(jc(10)); //3628800
  4. }
  5. //求斐波那契数列第m项
  6. public static int rabbit(int m){
  7. //递归出口
  8. if (m<3){
  9. return 1;
  10. }
  11. return rabbit(m-1)+rabbit(m-2);
  12. }
  13. //求阶乘
  14. public static int jc(int n){
  15. if (n==1){
  16. return 1;
  17. }
  18. return n*jc(n-1);
  19. }

递归遍历文件

  1. /*
  2. 递归
  3. 1.出口
  4. 2.规则
  5. */
  6. public static void main(String[] args) throws IOException {
  7. File f = new File("D:\\Java\\09_《Spring Boot企业级开发教材》");
  8. fileContent(f);
  9. }
  10. //遍历目录下所有文件的绝对路径
  11. public static void fileContent(File f) {
  12. File[] files = f.listFiles();
  13. if (files != null) {
  14. for (File file : files) {
  15. if (file.isDirectory()) {
  16. fileContent(file);
  17. } else {
  18. System.out.println(file.getAbsolutePath());
  19. }
  20. }
  21. }
  22. }

D:\Java\09《Spring Boot企业级开发教材》\工具包\apache-maven-3.6.0-bin.zip D:\Java\09《Spring Boot企业级开发教材》\工具包\apache-tomcat-9.0.16.zip D:\Java\09《Spring Boot企业级开发教材》\工具包\jdk-8u201-windows-i586.exe D:\Java\09《Spring Boot企业级开发教材》\工具包\jdk-8u201-windows-x64.exe D:\Java\09《Spring Boot企业级开发教材》\工具包\otp_win64_21.2.exe D:\Java\09《Spring Boot企业级开发教材》\工具包\rabbitmq-server-3.7.9.exe D:\Java\09《Spring Boot企业级开发教材》\工具包\redis-desktop-manager-0.8.8.384.exe D:\Java\09《Spring Boot企业级开发教材》\工具包\Redis-x64-3.2.100.zip D:\Java\09《Spring Boot企业级开发教材》\源代码\Spring Boot教材资源.rar D:\Java\09《Spring Boot企业级开发教材》\源代码\Spring Boot配套源代码.zip D:\Java\09_《Spring Boot企业级开发教材》\课后题答案\SpringBoot教材课后习题答案.doc

Process finished with exit code 0

IO流概述

  • 字节流
  • 字符流

    1. /*
    2. 字节流写入对象
    3. */
    4. public static void main(String[] args) throws IOException {
    5. //文件不存在则创建文件
    6. FileOutputStream fos = new FileOutputStream("src\\taobao.txt");
    7. //写入字节
    8. fos.write(97); //a
    9. fos.write(57); //9
    10. byte[] bt = {57, 56, 55, 54, 53, 52, 51, 50, 49, 48};
    11. fos.write(bt);
    12. byte[] bt1 = "abcde".getBytes();
    13. fos.write(bt1); //直接写入 abcde
    14. //指定长度写入,从索引0开始,长度为3的bt1数组写入
    15. fos.write(bt1,0,3);
    16. //释放资源,关闭文件输出流
    17. fos.close();
    18. }

    换行

    换行
    window: \r\n
    linux: \n
    mac: \r

    1. /*
    2. 字节流写入,异常处理,使程序更健壮
    3. */
    4. public static void main(String[] args) {
    5. //参数true,表示追加写入,默认false
    6. FileOutputStream fos = null;
    7. try {
    8. fos = new FileOutputStream("src\\taobao.txt", true);
    9. for (int i = 0; i < 10; i++) {
    10. fos.write("hello".getBytes());
    11. fos.write("\r\n".getBytes()); //换行
    12. }
    13. } catch (IOException e) {
    14. e.printStackTrace();
    15. } finally {
    16. if (fos != null) {
    17. try {
    18. fos.close();
    19. } catch (IOException e) {
    20. e.printStackTrace();
    21. }
    22. }
    23. }
    24. }

    读取

    当读到文件内容末位,返回值为-1

    1. public static void main(String[] args) throws IOException {
    2. //文件不存在则创建文件
    3. FileInputStream fis = new FileInputStream("src\\taobao.txt");
    4. //读取一个字节
    5. int by;
    6. //当读到文件内容末位,返回值为-1
    7. while ((by = fis.read()) != -1) {
    8. System.out.println((char) by);
    9. }
    10. //释放资源,关闭文件输出流
    11. fis.close();
    12. }

    复制文件内容

    1. public static void main(String[] args) throws IOException {
    2. //将文件java.md的内容复制到taobao.txt
    3. FileOutputStream fos = new FileOutputStream("src\\taobao.txt");//写入
    4. FileInputStream fis = new FileInputStream("D:\\Java\\java.md"); //读取
    5. //读取一个字节
    6. int by;
    7. //当读到文件内容末位,返回值为-1
    8. while ((by = fis.read()) != -1) {
    9. fos.write(by);
    10. }
    11. //释放资源,关闭文件输出流
    12. fos.close();
    13. fis.close();
    14. }

    读取文件—常用

    1. public static void main(String[] args) throws IOException {
    2. FileInputStream fis = new FileInputStream("src\\taobao.txt"); //读取
    3. //读取N个字节
    4. byte[] by = new byte[1024];
    5. int len;
    6. while ((len = fis.read(by)) != -1) {
    7. System.out.println(new String(by, 0, len));
    8. }
    9. //释放资源,关闭文件输出流
    10. fis.close();
    11. }

    复制图片

    1. public static void main(String[] args) throws IOException {
    2. FileOutputStream fos = new FileOutputStream("src\\aac.png");//写入
    3. FileInputStream fis = new FileInputStream("D:\\Album\\1号线.png"); //读取
    4. //读取N个字节
    5. byte[] by = new byte[1024];
    6. int len;
    7. while ((len = fis.read(by)) != -1) {
    8. //System.out.println(new String(by,0,len));
    9. fos.write(by);
    10. }
    11. //释放资源,关闭文件输出流
    12. fis.close();
    13. fos.close();
    14. }

    字节缓冲流 读写数据

    1. /*
    2. 字节缓冲流 读写数据
    3. */
    4. public static void main(String[] args) throws IOException {
    5. BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("src\\taobao.txt"));
    6. bos.write("hello ".getBytes());
    7. bos.write("world\n".getBytes());
    8. bos.close();
    9. BufferedInputStream bis = new BufferedInputStream(new FileInputStream("src\\taobao.txt"));
    10. byte[] by = new byte[1024];
    11. int len;
    12. while ((len = bis.read(by)) != -1) {
    13. System.out.println(new String(by, 0, len));
    14. }
    15. bis.close();
    16. }

    复制视频

    分别以4种方式复制

  • 字节复制

  • 字节数组复制
  • 缓冲流字节复制
  • 缓冲流字节数组复制 ——-最快!!!

    1. public static void main(String[] args) throws IOException {
    2. long start = System.currentTimeMillis();
    3. CopyVideo2();
    4. long end = System.currentTimeMillis();
    5. System.out.println("耗时:" + (end - start) + "毫秒");
    6. }
    7. //耗时:156813毫秒
    8. public static void CopyVideo() throws IOException {
    9. //将文件java.md的内容复制到taobao.txt
    10. FileOutputStream fos = new FileOutputStream("src\\code.mp4");//写入
    11. FileInputStream fis = new FileInputStream("D:\\草稿\\202104182103.mp4"); //读取
    12. //读取一个字节
    13. int by;
    14. //当读到文件内容末位,返回值为-1
    15. while ((by = fis.read()) != -1) {
    16. fos.write(by);
    17. }
    18. //释放资源,关闭文件输出流
    19. fos.close();
    20. fis.close();
    21. }
    22. //耗时:268毫秒
    23. public static void CopyVideo1() throws IOException {
    24. //将文件java.md的内容复制到taobao.txt
    25. FileOutputStream fos = new FileOutputStream("src\\code.mp4");//写入
    26. FileInputStream fis = new FileInputStream("D:\\草稿\\202104182103.mp4"); //读取
    27. //读取一个字节
    28. byte[] by = new byte[1024];
    29. int len;
    30. while ((len = fis.read(by)) != -1) {
    31. fos.write(by);
    32. }
    33. //释放资源,关闭文件输出流
    34. fos.close();
    35. fis.close();
    36. }
    37. //耗时:1244毫秒
    38. public static void CopyVideo2() throws IOException {
    39. BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("src\\code.mp4"));
    40. BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\草稿\\202104182103.mp4"));
    41. //读取一个字节
    42. int by;
    43. //当读到文件内容末位,返回值为-1
    44. while ((by = bis.read()) != -1) {
    45. bos.write(by);
    46. }
    47. bos.close();
    48. bis.close();
    49. }
    50. //耗时:95毫秒
    51. public static void CopyVideo3() throws IOException {
    52. BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("src\\code.mp4"));
    53. BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\草稿\\202104182103.mp4"));
    54. byte[] by = new byte[1024];
    55. int len;
    56. while ((len = bis.read(by)) != -1) {
    57. bos.write(by);
    58. }
    59. bos.close();
    60. bis.close();
    61. }

    字符流—编码-解码

    ```java

    1. //String s = "abc"; //[97,98,99]
    2. String s = "中国";

    //相同,说明默认采用utf-8编码

    1. //byte[] bys = s.getBytes(); //[-28, -72, -83, -27, -101, -67]
    2. byte[] bys = s.getBytes("utf-8"); //[-28, -72, -83, -27, -101, -67]
    3. //byte[] bys = s.getBytes("GBK"); //[-42, -48, -71, -6]
    4. System.out.println(Arrays.toString(bys));
  1. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/22084757/1636786828440-782fd577-73b2-421b-a615-fe19c2025d39.png#clientId=ua254ed71-1215-4&crop=0&crop=0&crop=1&crop=1&from=paste&id=uacd226df&margin=%5Bobject%20Object%5D&name=image.png&originHeight=526&originWidth=1073&originalType=binary&ratio=1&rotation=0&showTitle=false&size=238888&status=done&style=none&taskId=uae8bf92c-a1ec-430f-ad19-ebb4a41577e&title=)<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/22084757/1636786919193-12981e2a-7623-4a8a-88e3-a0aa59bd7fdd.png#clientId=ua254ed71-1215-4&crop=0&crop=0&crop=1&crop=1&from=paste&id=ub462fdf9&margin=%5Bobject%20Object%5D&name=image.png&originHeight=437&originWidth=981&originalType=binary&ratio=1&rotation=0&showTitle=false&size=206743&status=done&style=none&taskId=ubbac426c-0e0c-41bf-a923-9176ba19e16&title=)
  2. <a name="CptDh"></a>
  3. ## 读取文件
  4. ```java
  5. public static void main(String[] args) throws IOException {
  6. String s = "中国";
  7. byte[] bys = s.getBytes("GBK"); //[-42, -48, -71, -6]
  8. System.out.println(Arrays.toString(bys));
  9. //用何编码,应以其解码,否则会乱码
  10. String ss = new String(bys);
  11. System.out.println(ss); //�й�
  12. String ss1 = new String(bys,"GBK");
  13. System.out.println(ss1); //中国
  14. }
  1. /**
  2. * 字符流编码
  3. * @param args
  4. */
  5. public static void main(String[] args) throws IOException {
  6. //字符流写入
  7. OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("src\\owx.txt"), "utf-8");
  8. osw.write("中国"); //默认utf-8编码
  9. osw.write("你好世界", 2, 2); //只写入"世界"
  10. osw.flush(); //刷新,从缓冲区存入
  11. osw.close();
  12. //字符流读取数据
  13. InputStreamReader isr = new InputStreamReader(new FileInputStream("src\\Test01.java"), "utf-8");
  14. //一次读一个字符
  15. // int i;
  16. // while ((i=isr.read())!=-1){
  17. // System.out.print((char)i); //中国世界
  18. // }
  19. // 一次读一个数组
  20. char[] chars = new char[1024];
  21. int len;
  22. while ((len = isr.read(chars)) != -1) {
  23. System.out.println(new String(chars));
  24. }
  25. isr.close();
  26. }

字符流复制—便捷类FileWriter-FileReader

  1. public static void main(String[] args) throws IOException {
  2. FileReader fd = new FileReader("src\\taobao.txt");
  3. FileWriter fw = new FileWriter("src\\copy.txt");
  4. char[] chars = new char[1024];
  5. int len;
  6. while ((len=fd.read(chars))!=-1){
  7. fw.write(chars);
  8. }
  9. fd.close();
  10. fw.close();
  11. }

字符缓冲流

image.png
使用字节缓冲流复制文件

  1. public static void main(String[] args) throws IOException {
  2. BufferedReader br = new BufferedReader(new FileReader("src\\taobao.txt"));
  3. BufferedWriter bw = new BufferedWriter(new FileWriter("src\\copy.txt"));
  4. char[] chars = new char[1024];
  5. int len;
  6. while ((len=br.read(chars))!=-1){
  7. bw.write(chars);
  8. }
  9. br.close();
  10. bw.close();
  11. }

换行与一行读取

  1. public static void main(String[] args) throws IOException {
  2. BufferedReader br = new BufferedReader(new FileReader("src\\taobao.txt"));
  3. BufferedWriter bw = new BufferedWriter(new FileWriter("src\\copy.txt"));
  4. bw.write("你好");
  5. bw.newLine(); //换行
  6. String line; //一行一行读取
  7. while ((line = br.readLine())!=null){
  8. System.out.println(line);
  9. }
  10. br.close();
  11. bw.close();
  12. }

最常用方式— 复制文件

  1. public static void main(String[] args) throws IOException {
  2. BufferedReader br = new BufferedReader(new FileReader("src\\taobao.txt"));
  3. BufferedWriter bw = new BufferedWriter(new FileWriter("src\\copy.txt"));
  4. String line; //一行一行读取
  5. while ((line = br.readLine())!=null){
  6. bw.write(line);
  7. bw.newLine();
  8. bw.flush();
  9. }
  10. br.close();
  11. bw.close();
  12. }
  13. }

image.png
image.png

点名

  1. public class Demo {
  2. /**
  3. * 从文件中随机抽取一行
  4. * @param args
  5. * @throws IOException
  6. */
  7. public static void main(String[] args) throws IOException {
  8. ArrayList<String> arr = new ArrayList<>();
  9. BufferedReader br = new BufferedReader(new FileReader("src\\taobao.txt"));
  10. String line; //一行一行读取
  11. while ((line = br.readLine())!=null){
  12. arr.add(line);
  13. }
  14. br.close();
  15. Random random = new Random();
  16. int index = random.nextInt(arr.size());
  17. String name = arr.get(index);
  18. System.out.println(name);
  19. }
  20. }

集合对象写入

  1. public static void main(String[] args) throws IOException {
  2. ArrayList<Student> students = new ArrayList<>();
  3. Student s1 = new Student("鞠婧祎",25,"武汉");
  4. Student s2 = new Student("马保国",60,"重庆");
  5. Student s3 = new Student("薛之谦",25,"上海");
  6. students.add(s1);
  7. students.add(s2);
  8. students.add(s3);
  9. BufferedWriter bw = new BufferedWriter(new FileWriter("src\\copy.txt"));
  10. for (Student s:students){
  11. bw.write(s.getName()+"--"+s.getAge()+"--"+s.getAddress());
  12. bw.newLine();
  13. }
  14. bw.close();
  15. }

复制单级文件夹—-有问题

  1. public static void main(String[] args) throws IOException {
  2. File file = new File("src\\duoc");
  3. String srcname = file.getName();
  4. File dest = new File("TestStudy",srcname);
  5. if (!dest.exists()){
  6. dest.mkdir();
  7. }
  8. File[] listFile = file.listFiles();
  9. for (File f:listFile){
  10. String srcFileName = f.getName();
  11. File destFile = new File(dest,srcFileName);
  12. copyFile(f,destFile);
  13. }
  14. }
  15. public static void copyFile(File srcFile,File destFile) throws IOException {
  16. BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
  17. BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
  18. byte[] bys = new byte[1024];
  19. int len;
  20. while ((len=bis.read(bys))!=-1){
  21. bos.write(bys,0,len);
  22. }
  23. bos.close();
  24. bis.close();
  25. }

复制多级文件夹—递归

….

打印流复制文件

只能写不能读
printWriter

对象序列化流

ObjectOutputStream

对象反序列化流

ObjectItputStream

关键字 修饰符transient

使用transient修饰 成员变量将不参与序列化

Properties集合类

猜数字游戏,限制游戏次数

  1. public class Demo {
  2. /**
  3. * 从文件中随机抽取一行
  4. * @param args
  5. * @throws IOException
  6. */
  7. public static void main(String[] args) throws IOException {
  8. Properties prop = new Properties();
  9. FileReader fr = new FileReader("src\\owx.txt");
  10. //文件写入 count = 0
  11. prop.load(fr);
  12. fr.close();
  13. String count = prop.getProperty("count");
  14. int number = Integer.parseInt(count);
  15. if (number>2){
  16. System.out.println("请充值后继续");
  17. }else{
  18. Demo.GuessNumber();
  19. number++;
  20. prop.setProperty("count",String.valueOf(number));
  21. FileWriter fw = new FileWriter("src\\owx.txt");
  22. prop.store(fw,null);
  23. fw.close();
  24. }
  25. }
  26. public static void GuessNumber(){
  27. Random r = new Random();
  28. int number = r.nextInt(100)+1;
  29. while (true){
  30. Scanner sc = new Scanner(System.in);
  31. System.out.print("请输入猜的数值:");
  32. int guessNum = sc.nextInt();
  33. if (guessNum>number){
  34. System.out.println("大了哦");
  35. }else if (guessNum<number){
  36. System.out.println("小了点");
  37. }else{
  38. System.out.println("猜对了");
  39. break;
  40. }
  41. }
  42. }
  43. }

进程与线程

image.png

多线程的实现方式

方式一:继承Thread类

  1. 继承Tread类
  2. 重写run()方法
  3. 创建类对象
  4. 启动线程

    1. class Demo{
    2. public static void main(String[] args) {
    3. MyThread m1 = new MyThread();
    4. MyThread m2 = new MyThread();
    5. //普通方式
    6. // m1.run();
    7. // m2.run();
    8. //以start启动线程,再由JVM调用run方法
    9. //不会等到m1的run方法跑完就会执行m2的run方法
    10. m1.start();
    11. m2.start();
    12. }
    13. }
    1. public class MyThread extends Thread {
    2. @Override
    3. public void run() {
    4. int i = 0;
    5. while (i<100){
    6. System.out.println(i++);
    7. }
    8. }
    9. }

    设定与获取线程名称

    不设置获取默认值
    线程名称默认值
    第一次调用: Thread-0
    第二次调用: Thread-1

    1. public static void main(String[] args) {
    2. MyThread m1 = new MyThread();
    3. MyThread m2 = new MyThread();
    4. //普通方式
    5. // m1.run();
    6. // m2.run();
    7. //以start启动线程,再由JVM调用run方法
    8. //不会等到m1的run方法跑完就会执行m2的run方法
    9. m1.setName("飞机");
    10. System.out.println(m1.getName());
    11. m1.start();
    12. m2.setName("大炮");
    13. System.out.println(m2.getName());
    14. m2.start();
    15. }

    或者提供一个带参构造方法

    1. public static void main(String[] args) {
    2. MyThread m1 = new MyThread("飞机");
    3. MyThread m2 = new MyThread("大炮");
    4. //普通方式
    5. // m1.run();
    6. // m2.run();
    7. //以start启动线程,再由JVM调用run方法
    8. //不会等到m1的run方法跑完就会执行m2的run方法
    9. System.out.println(m1.getName());
    10. m1.start();
    11. System.out.println(m2.getName());
    12. m2.start();
    13. }
    1. class Demo{
    2. public static void main(String[] args) {
    3. //返回当前正在执行的线程名称
    4. System.out.println(Thread.currentThread().getName());
    5. //main
    6. }
    7. }

    线程调度模型

  • 分时调度模型
  • 抢占式调度模型

image.png

java使用的是抢占式调度模型
随机性
优先级—存在范围 [1,10]
默认值— 5

  1. m1.setPriority(10);
  2. m3.setPriority(1);

线程控制

image.png

  1. @Override
  2. public void run() {
  3. int i = 0;
  4. while (i<100){
  5. System.out.println(getName()+"--"+i++);
  6. try {
  7. Thread.sleep(1000); //每隔1秒执行每个线程一次
  8. } catch (InterruptedException e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. }
  1. public static void main(String[] args) {
  2. MyThread m1 = new MyThread("飞机");
  3. MyThread m2 = new MyThread("高铁");
  4. MyThread m3 = new MyThread("骑车");
  5. // m1.setPriority(10);
  6. // m3.setPriority(1);
  7. m1.start();
  8. try {
  9. m1.join(); //只有m1线程停止后,才执行其他线程
  10. } catch (InterruptedException e) {
  11. e.printStackTrace();
  12. }
  13. m2.start();
  14. m3.start();
  15. }

守护线程 —不是立即结束!!

  1. class Demo{
  2. public static void main(String[] args) {
  3. MyThread m1 = new MyThread("飞机");
  4. MyThread m2 = new MyThread("高铁");
  5. MyThread m3 = new MyThread("骑车");
  6. // m1.setPriority(10);
  7. // m3.setPriority(1);
  8. m1.start();
  9. m2.start();
  10. m2.setDaemon(true); //设定为守护线程,主线程结束后,守护线程应也马上结束
  11. m3.start();
  12. m3.setDaemon(true);
  13. Thread.currentThread().setName("主线程");
  14. int i = 0;
  15. while (i<10){
  16. System.out.println(Thread.currentThread().getName()+"--"+i++);
  17. }
  18. }
  19. }

线程的生命周期

image.png

方式二:实现Runnable接口

  1. public class MyThread implements Runnable {
  2. public MyThread() {
  3. }
  4. @Override
  5. public void run() {
  6. int i = 0;
  7. while (i<100){
  8. System.out.println(Thread.currentThread().getName()+"--"+i++);
  9. // try {
  10. // Thread.sleep(1000); //每隔1秒执行每个线程一次
  11. // } catch (InterruptedException e) {
  12. // e.printStackTrace();
  13. // }
  14. }
  15. }
  16. }
  1. class Demo{
  2. public static void main(String[] args) {
  3. MyThread m = new MyThread();
  4. Thread t1 = new Thread(m,"飞机");
  5. Thread t2 = new Thread(m,"火车");
  6. t1.start();
  7. t2.start();
  8. }
  9. }

image.png

卖票案例

image.png

  1. public class MyThread implements Runnable {
  2. private int tickets = 100; //总票数
  3. private Object obj = new Object();
  4. public MyThread() {
  5. }
  6. @Override
  7. public void run() {
  8. while (true){
  9. //解决线程同步安全问题,将不会出现两个窗口同时出售同一张票的情况
  10. synchronized (obj){
  11. try {
  12. Thread.sleep(100);
  13. } catch (InterruptedException e) {
  14. e.printStackTrace();
  15. }
  16. if(tickets > 0){
  17. System.out.println(Thread.currentThread().getName()+"正在出售第"+tickets--+"张票");
  18. }
  19. }
  20. }
  21. }
  22. }
  1. public static void main(String[] args) {
  2. MyThread m = new MyThread();
  3. Thread t1 = new Thread(m,"VIP窗口");
  4. Thread t2 = new Thread(m,"普通窗口");
  5. Thread t3 = new Thread(m,"附加窗口");
  6. t1.setPriority(8);
  7. t3.setPriority(2);
  8. t1.start();
  9. t2.start();
  10. t3.start();
  11. }

同步方法锁定this

以修饰符 synchronized 修饰方法
image.png