> 文章列表 > 【java进阶10:IO流】File类、序列化与反序列化、作业:目录拷贝、IO+Properties的联合应用

【java进阶10:IO流】File类、序列化与反序列化、作业:目录拷贝、IO+Properties的联合应用

【java进阶10:IO流】File类、序列化与反序列化、作业:目录拷贝、IO+Properties的联合应用

目录

IO流

文件专属

缓冲流以及转换流

数据流

标准流

File类

作业:拷贝目录

对象流


IO流

  1. IO流,什么是IO?

    I:Input 、O:Output。通过IO可以完成硬盘文件的读和写。

    在这里插入图片描述

  2. IO流的分类:

    有多种分类方式:

    • 一种方式是按照流的方向进行分类:以内存为参照物。

      ​ 往内存中去,叫:输入(Input),或者叫:读(Read)

      ​ 从内存中出,叫:输出(Output),或者叫:写(Write)

    • 另一种方式是按照读取数据方式不同进行分类:

      • 字节

        ​ 有的流是按照字节的方式读取数据,一次读取一个字节byte(8个二进制位)。这种流是万能的,什么类型的文件都可以读取。包括:文本文件、图片、声音文件、视频文件等······

        ​ 假设文件file.text:a中国bc张三fe,使用字节流的方式读取:

        ​ 第一次读:一个字节,刚好读到 ‘a’

        ​ 第二次读:一个字节,刚好读到 ‘中’ 字符的一半

        ​ 第三次读:一个字节,刚好读到 ‘中’ 字符的另一半

      • 字符流

        ​ 有的流是按照字符的方式读取数据的,一次读取一个字符,这种流是问了方便读取普通文本而存在的,这种流不能读取:图片、声音、视频等,甚至连word文件都无法读取。只能读取:纯文本文件。

      ​ 假设文件file.text:a中国bc张三fe,使用字符流的方式读取:

      ​ 第一次读: ‘a’ 字符 (‘a’ 字符在windows系统中占用1个字节)

      ​ 第二次读: ‘中’ 字符(‘中’ 字符在windows系统中占用2个字节)

      ​ 第三次读: ‘国’ 字符 (‘国’ 字符在windows系统中占用2个字节)

      综上所述,流的分类:

      ​ 输入流、输出流;字节流、字符流

  3. java中的IO流都已经写好了,我们不需要关心。

    ​ 我们主要掌握:java中提供了哪些流、每个流的特点、每个流对象的擦汗给你用方法

    ​ java中所有的流都是在:java.io.*; 下

    ​ 我们主要研究:如何new流对象、流对象的哪个方法是读,哪个方法是写?

  4. java IO流这里有四大家族:

    四大家族的首领:

    ​ java.io.InputStream 字节输入流

    ​ java.io.OutputStream 字节输出流

    ​ java.io.Reader 字符输入流

    ​ java.io.Writer 字符输出流

    这四个类都是抽象类。(abstract)

    所有的流都实现了:java.io.Closeable接口

    ​ 是可关闭的,都有Close()方法。流毕竟是一个管道,这个是内存和硬盘之间的通道,用完之后一定要关闭。不然会耗费(占用)很多资源,养成好习惯,用完流一定要关闭。

    所有的输出流都实现了:java.io.Flushable接口

    ​ 是可刷新的,都有flush()方法。要养成习惯:输出流在最终输出后,一定要flush()刷新一下

    ​ 这个刷新表示将流当中未输出的数据强行输出。(清空管道),刷新的作用就是清空流

    ​ 注意:如果未使用flush()刷新/清空流,可能会导致丢失数据。

    注意:

    ​ 在java中只要 ”类名 “ 以”Stream“结尾的都是字节流

    ​ 以”Reader/Writer“结尾的都是字符流

  5. java.io报下需要掌握的流有16个:

    //文件专属:java.io.FileInputStream(掌握)java.io.FileOutputStream(掌握)java.io.FileReaderjava.io.FileWriter//转换流:将字节流转换成字符流java.io.InputStreamReaderjava.io.OutputStreamWriter//缓冲流专属:java.io.BufferedReaderjava.io.BufferedWriterjava.io.BufferedInputStreamjava.io.BufferedOutputStream//数据流专属java.io.DataInputStreamjava.io.DataOutputStream//标准输出流java.io.PrintWriterjava.io.PrintStream(掌握)//对象流专属java.io.ObjectInputStream(掌握)java.io.ObjectOutputStream(掌握)
    /*	重点:参与序列化的类型必须实现java.io.Serializable接口。并且建议将序列化版本号手动的写出来:private static final long serialVersionUID = 123L;
    */
    
  6. java.io.File类

  7. IO +Properties联合使用

    /*	IO流:文件的读和写Properties:是一个Map集合,key和value都是String类型
    */
    

文件专属

  1. 文件字节输入流:java.io.FileInputStream:

    package io;import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;/*java.io.FileInputStream:1、文件字节输入流(万能的,任何类型文件都可以采用这个流来读)2、字节的方式,完成 输入/读 的操作 (硬盘 --输入--> 内存)*/
    public class FileInputStreamText01 {public static void main(String[] args) {//创建文件字节输入对象。在try外定义变量,使fis为空,当fis为空时关闭流,就可以使用finally语句在最后关闭流FileInputStream fis = null;try {//文件路径:D:\\Program Files (x86)\\IntelliJ IDEA 2019.3.3\\io流(IDEA会自动把\\变成\\\\,因为在java中\\表示转义)//以下是采用了:绝对路径的方式//FileInputStream fis = new FileInputStream("D:\\\\Program Files (x86)\\\\IntelliJ IDEA 2019.3.3\\\\io流\\\\temp");//      \\\\写成/也是可以的fis = new FileInputStream("D:/Program Files (x86)/IntelliJ IDEA 2019.3.3/io流/temp.txt");//开始读int readDate = fis.read();  //这个方法的返回是:读取到的“字节”本身System.out.println(readDate);//97readDate = fis.read();System.out.println(readDate);   //98readDate = fis.read();System.out.println(readDate);   //99readDate = fis.read();System.out.println(readDate);   //100readDate = fis.read();System.out.println(readDate);   //101readDate = fis.read();System.out.println(readDate);   //102//已经读到文件的末尾了,再读时读不到任何数据,返回:-1readDate = fis.read();System.out.println(readDate);   //-1readDate = fis.read();System.out.println(readDate);   //-1readDate = fis.read();System.out.println(readDate);   //-1} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {//在finally语句块当中确保流一定关闭if (fis != null) {//关闭流的前提是:流不是null。流是null的时候没必要关闭,同时避免了空指针异常try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}
    }
  2. 初步改进

    package io;import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;/*对第一个程序进行改进,读数据时使用循环分析这个程序缺点:一次读取一个字节byte,*/
    public class FileInputStreamText02 {public static void main(String[] args) {FileInputStream fis = null;try {fis = new FileInputStream("D:/Program Files (x86)/IntelliJ IDEA 2019.3.3/io流/temp.txt");
    /*            while(true){int readDate = fis.read();if(readDate == -1){break;}System.out.println(readDate);}*///改进while循环int readDate = 0;//给个初始值使循环可以进行while((readDate = fis.read()) != -1){//只要还有数据,readDate不会等于-1,读取完返回-1,-1 != -1  返回false,结束循环System.out.println(readDate);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}
    }
    
  3. 再次改进

    package io;import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;/*int read(byte[] b)一次最多读取b.length个字节减少硬盘和内存的交互,提高程序的执行效率,在byte[] 数组当中读*/
    public class FileInputStreamText03 {public static void main(String[] args) {FileInputStream fis = null;try {//如果使用相对路径:从当前所在位置为起点,开始寻找。//IDEA默认的当前路径在:工程project的根就是IDEA的默认路径。//fis  = new FileInputStream(temp.text);fis = new FileInputStream("D:\\\\Program Files (x86)\\\\IntelliJ IDEA 2019.3.3\\\\io流\\\\temp.txt");//开始读,采用byte数组,一次读取多个字节。最多读取“数组.length”个字节byte[] bytes = new byte[4];  //准备一个4长度的byte数组,一次最多读取四个字节//这个方法的返回值是:读取到的字符数量(不是字符本身)int readCount = fis.read(bytes);System.out.println(readCount);  //第1次读到4个字节//将字符数组转换成字符串//System.out.println(new String(bytes));//abcd//不应该都转,而是读到几个字节转几个字节//从第一个开始转换,读到几个转几个//                            数组,起始位置,读几位System.out.println(new String(bytes,0,readCount));readCount = fis.read(bytes);    //第2次只能读到2个字节System.out.println(readCount);  //2//System.out.println(new String(bytes));//efcdSystem.out.println(new String(bytes,0,readCount));readCount = fis.read(bytes);    //第3次1个字节都没读到,返回-1System.out.println(readCount);  //-1} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}
    }
    
  4. 最终版本:采用边读边写的方式

    package io;import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;/*最终版,需要掌握*/
    public class FileInputStreamText04 {public static void main(String[] args) {FileInputStream fis = null;try {fis = new FileInputStream("D:\\\\Program Files (x86)\\\\IntelliJ IDEA 2019.3.3\\\\io流\\\\temp.txt");//测试可不可以读新编写的helloworldfis = new FileInputStream("D:\\\\Program Files (x86)\\\\IntelliJ IDEA 2019.3.3\\\\io流\\\\HelloWorld.txt");//准备一个byte数组byte[] bytes = new byte[4];/*            while(true){int readCount = fis.read(bytes);if(readCount == -1){break;}//可以执行到这里,说明读取到了数据,把数组转换成字符串,读到多少个,转换多少个System.out.print(new String(bytes,0,readCount));}*///改进int readCount = 0;while((readCount = fis.read(bytes)) != -1){System.out.print(new String(bytes,0,readCount));}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}
    }
    
  5. FileInputStream类的其他常用方法

    package io;import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;/*FileInputStream类的其他常用方法int available() 返回流当中剩余的没有读到的字节数量。long skip(long n) 跳过几个字节不读。*/
    public class FileInputStreamText05 {public static void main(String[] args) {FileInputStream fis = null;try {fis = new  FileInputStream("D:\\\\Program Files (x86)\\\\IntelliJ IDEA 2019.3.3\\\\io流\\\\temp.txt");System.out.println("整个文件可以读取的字节:"+fis.available());/*            fis.read();   //读了1个//还剩下可以读的字节数量是:int readByte = fis.available();System.out.println("未读字节:"+readByte);//5*///这个方法有什么用?byte[] bytes = new byte[fis.available()];   //这种方式不太适合太大的文件,因为byte[] 数组不能太大//不需要循环了,直接读一次就可以//fis.read(bytes);//System.out.println(new String(bytes));  //abcdef//skip跳过几个字节不读取,这个方法也可能跟以后会用!fis.skip(3);System.out.println(fis.read()); //100} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally{if (fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}
    }
    
  6. 文件字节输出流,负责写。从内存到硬盘

    package io;import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;/*文件字节输出流,负责写。从内存到硬盘*/
    public class FileOutputStreamText01 {public static void main(String[] args) {FileOutputStream fos = null;try {//myfile文件不存在的时候会自动新建//这种方式谨慎使用,这种方式会先将原文件清空,然后重新写入。//fos = new FileOutputStream("myfile");//以追加的方式在文件末尾写入,不会清空原文件内容//true:表示追加。    false/不写:清空后写入fos = new FileOutputStream("myfile",true);//开始写byte[] bytes = {97,98,99,100};//将byte数组全部写出fos.write(bytes);//abcd//将byte数组的一部分写出fos.write(bytes,0,2);//ab//字符串String s = "我是一个中国人,我骄傲!";//将字符串转换成byte数组byte[] bs = s.getBytes();//写fos.write(bs);//写完之后,最后一定要刷新fos.flush();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {if (fos != null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}}}
    }
    
  7. 使用FileInputStream + FileOutputStream完成文件的拷贝。

    package io;
    /*使用FileInputStream + FileOutputStream完成文件的拷贝。拷贝的过程应该是一边读,一边写。使用以上的字节流拷贝文件的时候,文件类型随意,什么文件都能拷贝。*/import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;public class Copy01 {public static void main(String[] args) {FileInputStream fis = null;FileOutputStream fos = null;try {//创建一个输入流对象fis  = new FileInputStream("C:\\\\Users\\\\qishi\\\\Desktop\\\\typora   markdown学习\\\\java笔记\\\\进阶\\\\巴士骚m跪撸.mp4");//创建一个输出流对象fos = new FileOutputStream("D:\\\\Program Files (x86)\\\\IntelliJ IDEA 2019.3.3\\\\io流\\\\fuzhi\\\\巴士骚m跪撸.mp4");//最核心的:一边读,一边写byte[] bytes = new byte[1024 * 1024]; // 1MB(1024*1024个字节,就是1024KB,就是1MB。一次最多拷贝1MB)int readCount = 0;while ((readCount = fis.read(bytes)) != -1){fos.write(bytes,0,readCount);}//刷新,输出流最后要刷新fos.flush();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {//分开try,不能一起try。//一起try的时候,其中一个出现异常,可能会影响到另一个流的关闭if (fos != null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}if(fis != null){try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}
    }
    
  8. 文件字符输入流FileReader:

    package io;import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;/*FileReader:文件字符输入流,只能读取普通文本。读取文本内容时,比较方便、快捷。*/
    public class FileReaderText {public static void main(String[] args) {FileReader reader = null;try {//创建文件字符输入流reader = new FileReader("myfile");//开始读char[] chars = new char[4];//往char数组中读reader.read(chars);//   按照字符的方式读:第一次a, 第二次:b ,第三次:我,第四次:是for(char c :chars){System.out.println(c);}//读取全部
    /*            int readCount = 0;while((readCount = reader.read(chars)) != -1){System.out.print(new String(chars,0,readCount));}*/} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {reader.close();} catch (IOException e) {e.printStackTrace();}}}
    }
    
  9. FileWriter:文件字符输出流

    package io;import java.io.FileWriter;
    import java.io.IOException;/*FileWriter:文件字符输出流,写只能输出普通文本。*/
    public class FileWriterText {public static void main(String[] args) {FileWriter out = null;try {//创建文件字符输出流对象//out = new FileWriter("myWriter"); //清空后写入//使用追加的方式out = new FileWriter("myWriter",true);//开始写char[] chars = {'我','是','中','国','人'};out.write(chars);out.write(chars,2,3);out.write("我是一名java软件攻城狮");//写出一个换行符out.write("\\n");out.write("hello world!");//刷新out.flush();} catch (IOException e) {e.printStackTrace();}finally {try {out.close();} catch (IOException e) {e.printStackTrace();}}}
    }
    
  10. 使用FileReader FileWriter进行拷贝的话,只能拷贝“普通文本”文件

    package io;import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;/*使用FileReader FileWriter进行拷贝的话,只能拷贝“普通文本”文件*/
    public class Copy02 {public static void main(String[] args) {FileReader in = null;FileWriter out = null;try {//创建一个输入流对象:读in = new FileReader("IO\\\\src\\\\io\\\\Copy02.java");//java文件也属于普通文本文件,运行时运行的是class文件//能用记事本编辑的都是普通文本文件,普通文本文件与后缀无关,不一定都是.txt//创建一个输出流对象:写out = new FileWriter("Copy02.java");//一边读,一边写//java中一个char占用两个字节char[] chars = new char[1024* 512]; //1MBint readCount = 0;while((readCount = in.read(chars)) != -1){out.write(chars,0,readCount);}//刷新,输出流的最后要刷新out.flush();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}if (out != null) {try {out.close();} catch (IOException e) {e.printStackTrace();}}}}
    }

    文件复制原理

    在这里插入图片描述

缓冲流以及转换流

  1. BufferedReader: 待用缓冲区的字符输入流。

    package io;import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;/*BufferedReader:待用缓冲区的字符输入流。使用这个流的时候不需要自定义char数组,或者说不需要定义byte数组。自带缓冲*/
    public class BufferedReaderText01 {public static void main(String[] args) throws IOException {FileReader reader = new FileReader("Copy02.java");//当一个流的构造方法中需要一个流的时候,这个被传进来的流叫:节点流。//外部负责包装的这个流叫:包装流。还叫:处理流//像当前这个程序来说:FileReader就是一个节点流,BufferedReader就是包装流/处理流BufferedReader br = new BufferedReader(reader);//读一行
    /*        String firstLine = br.readLine();//第一行System.out.println(firstLine);String secondLine = br.readLine();//第二行System.out.println(secondLine);String thirdLine = br.readLine();//第三行System.out.println(thirdLine);*///循环读取//br.readLine()方法读一个文本行,但不带换行符String s = null;while((s = br.readLine())!= null){System.out.println(s);}//关闭流。//对于包装流来说,只需要关闭最外层流就行,里面的节点流会自动关闭。(可以看源代码)br.close();}
    }
    
  2. 转换流:InputStreamReader

    package io;import java.io.*;/*转换流:InputStreamReader*/
    public class BufferedReaderText02 {public static void main(String[] args) {try {//字节流
    /*            FileInputStream in = new FileInputStream("Copy02.java");//通过转换流转换(InputStreamReader将字节流转换成字符流)//in是节点流,reader是包装流InputStreamReader reader = new InputStreamReader(in);//这个构造方法只能传一个字符流,不能传字节流//reader是节点流,br是包装流BufferedReader br = new BufferedReader(reader);*///合并以上代码BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("Copy02.java")));String line = null;while((line =br.readLine()) != null){System.out.println(line);}//关闭最外层br.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
    }
    
  3. BufferedWriter:带有缓冲的字符输出流

    package io;import java.io.*;/*BufferedWriter:带有缓冲的字符输出流*/
    public class BufferedWriterText {public static void main(String[] args) {try {//BufferedWriter out = new BufferedWriter(new FileWriter("Copy"));BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Copy",true)));out.write("hello world");out.write("\\n");out.write("hello kitty");//刷新out.flush();//关闭最外层out.close();} catch (IOException e) {e.printStackTrace();}}
    }
    

数据流

  1. java.io.DataOutputStream:数据专属的流。

    package io;import java.io.DataOutputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;/*java.io.DataOutputStream:数据专属的流。这个流可以将数据连同数据的类型一并写入文件注意:这个文件不是普通文本文档(这个文件使用记事本打不开)*/
    public class DataOutputStreamText {public static void main(String[] args) {//创建数据专属的字节输出流try {DataOutputStream dos = new DataOutputStream(new FileOutputStream("data"));//写数据byte b = 100;short s = 200;int i = 300;long l = 400L;float f = 3.0F;double d = 3.14;boolean sex = true;char c = 'a';//写dos.writeByte(b);   //把数据以及数据的类型一并写入到文件当中dos.writeShort(s);dos.writeInt(i);dos.writeLong(l);dos.writeFloat(f);dos.writeDouble(d);dos.writeBoolean(sex);dos.writeChar(c);//刷新dos.flush();//关闭最外层dos.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
    }
    
  2. DataInputStream:数据字节输入流

    package io;import java.io.DataInputStream;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;/*DataInputStream:数据字节输入流DataOutputStream写的文件,只能使用DataInputStream去读,并且读的时候需要提前知道写入的顺序读的顺序需要和写的顺序一致,才可以正常取出数据。*/
    public class DataInputStreamText {public static void main(String[] args) {try {DataInputStream dis = new DataInputStream(new FileInputStream("data"));//开始读byte b = dis.readByte();short s = dis.readShort();int i = dis.readInt();long l = dis. readLong();float f = dis.readFloat();double d = dis.readDouble();boolean sex = dis.readBoolean();char cc = dis.readChar();System.out.println(b);System.out.println(s);System.out.println(i+666);System.out.println(l);System.out.println(f);System.out.println(d);System.out.println(sex);System.out.println(cc);//关闭流dis.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
    }
    

标准流

  1. java.io.PrintStream:标准的字节输出流,默认输出到控制台。

    package io;import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.PrintStream;/*java.io.PrintStream:标准的字节输出流,默认输出到控制台。*/
    public class PrintStreamText {public static void main(String[] args) {//联合起来写System.out.println("hello world");//分开写PrintStream ps = System.out;ps.println("hehe");ps.println("haha");//标准输出流不需要手动close()关闭/*之前使用过的方法和属性System.gc();System.currentTimeMillis();PrintStream ps = System.out;System.exit(0);System.arraycopy();*///可以改变标准输出流的输出方向吗?可以try {//标准输出流不再指向控制台,指向“log”文件PrintStream printStream = new PrintStream(new FileOutputStream("log",true));//追加输出//修改输出方向:将输出方向修改到“log”文件System.setOut(printStream);//再输出System.out.println("hello world");System.out.println("hello kitty");} catch (FileNotFoundException e) {e.printStackTrace();}}
    }
    
  2. 日志工具,改变输出方向

    package io;import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.PrintStream;
    import java.text.SimpleDateFormat;
    import java.util.Date;/*日志工具*/
    public class Logger {//记录日志的方法public static void log(String msg){try {//指向一个日志文件PrintStream out = new PrintStream(new FileOutputStream("log.txt",true));//改变输出方向System.setOut(out);//日期:当前时间Date nowTime = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");String strTime = sdf.format(nowTime);System.out.println(strTime +":"+msg);} catch (FileNotFoundException e) {e.printStackTrace();}}
    }
    

    测试

    package io;/*测试工具类是否好用*/
    public class LogText {public static void main(String[] args) {//测试工具类是否好用Logger.log("调用了System类的gc()方法,建议启动垃圾回收");Logger.log("调用了UserService的doSome()方法");Logger.log("用户尝试进行登录,验证失败");Logger.log("我非常喜欢这个日志工具哦!");}
    }
    

File类

  1. File是什么

    package io;import java.io.File;
    import java.io.IOException;/*File1、File类和四大家族没有关系,所以File类不能完成文件的读和写2、File对象代表什么?文件和目录路径名的抽象表达形式。C:\\program 这是一个File对象C:\\program\\read.txt 这也是File对象一个File对象有可能对应的是目录,也可能是文件。File只是一个路径名的抽象表达形式。3、需要掌握File类中的常用方法。*/
    public class FileText01 {public static void main(String[] args) throws IOException {//创建一个File对象File f1 = new File("D:\\\\file");//判断是否存在D:\\fileSystem.out.println(f1.exists());//如果D:\\file不存在,则以文件的形式创建出来
    /*        if(!f1.exists()){f1.createNewFile();//以文件的形式创建}*///如果D:\\file不存在,则以目录的形式创建出来
    /*        if(!f1.exists()){f1.mkdir();//以目录的形式创建}*///创建多重目录File f2 = new File("D:/a/b/c/d/e/f");
    /*        if(!f2.exists()){//多重目录的形式创建f2.mkdirs();}*/File f3 = new File("D:\\\\下载\\\\小说啦啦啦啦 等1个文件\\\\完1111\\\\……\\\\小说啦啦啦啦\\\\三国.doc");//获取文件的父路径String parePath = f3.getParent();System.out.println(parePath);//D:\\下载\\小说啦啦啦啦 等1个文件\\完1111\\……\\小说啦啦啦啦//以file对象的形式返回File pareFile = f3.getParentFile();System.out.println("获取绝对路径:"+pareFile.getAbsolutePath());//获取绝对路径:D:\\下载\\小说啦啦啦啦 等1个文件\\完1111\\……\\小说啦啦啦啦//获取绝对方法File f4 = new File("Copy");System.out.println("绝对路径"+f4.getAbsolutePath());//D:\\Program Files (x86)\\IntelliJ IDEA 2019.3.3\\javaSE\\Copy}
    }
    
  2. File类中的常用方法

    package io;import java.io.File;
    import java.text.SimpleDateFormat;
    import java.util.Date;/*
    File类的常用方法*/
    public class FileText02 {public static void main(String[] args) {File f1 = new File("D:\\\\下载\\\\小说啦啦啦啦 等1个文件\\\\完1111\\\\……\\\\小说啦啦啦啦\\\\三国.doc");//获取文件名System.out.println("文件名:"+f1.getName());//三国.doc//判断是否为一个目录System.out.println(f1.isDirectory());//false//判断是否是一个文件System.out.println(f1.isFile());//true//获取文件最后一次修改时间long haoMiao = f1.lastModified();   //这个毫秒是从1970年到现在的总毫秒数。//将毫秒数转换成日期Date time = new Date(haoMiao);SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");String strTime = sdf.format(time);System.out.println(strTime);//获取文件大小System.out.println(f1.length());//15872}
    }
    
  3. File中的listFiles方法

    package io;import java.io.File;/*
    File中的listFiles方法*/
    public class FileText03 {public static void main(String[] args) {//File[] listFiles()    获取当前目录下的所有子文件File f = new File("D:\\\\是事实\\\\可");File[] files = f.listFiles();for(File file : files){System.out.println(file.getName());}}
    }
    

作业:拷贝目录

有些方面还可以更好,以后修改

package io;import java.io.*;/*拷贝目录*/
public class CopyAll {public static void main(String[] args) {//拷贝源File srcFile = new File("D:\\\\course");//拷贝目标File destFile = new File("C:\\\\");//调用方法拷贝copyDir(srcFile,destFile);}/* 拷贝目录* @param srcFile   拷贝源* @param destFile  拷贝目标*/private static void copyDir(File srcFile, File destFile) {if(srcFile.isFile()){//是文件时需要拷贝。一边读一边写FileInputStream fis = null;FileOutputStream fos = null;try {//读这里:     D:\\course\\SQL SERVER笔记\\01数据库结构.txtfis = new FileInputStream(srcFile);//写:         C:\\course\\SQL SERVER笔记\\01数据库结构.txt//拼接:String path = (destFile.getAbsolutePath().endsWith("\\\\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\\\")+srcFile.getAbsolutePath().substring(3);fos = new FileOutputStream(path);//一边读,一边写byte[] bytes = new byte[1024 * 1024]; // 1MB(1024*1024个字节,就是1024KB,就是1MB。一次最多拷贝1MB)int readCount = 0;while ((readCount = fis.read(bytes)) != -1){fos.write(bytes,0,readCount);}//刷新fos.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();}}}//srcFile是一个文件,递归结束。return;}//获取源下面的子目录File[] files = srcFile.listFiles();for(File file : files){//获取所有文件(包括目录和文件)的绝对路径//System.out.println(file.getAbsolutePath());if(file.isDirectory()){//新建对应目录//System.out.println(file.getAbsolutePath());//源目录   D:\\course//目标目录 C:\\courseString srcDir = file.getAbsolutePath();//如果是多重目录,在后面相加时,中间可能会少个\\\\,所以这里用三目运算符判断结尾是否是\\\\,endswith(""):判断是否以""什么结尾String destDir =(destFile.getAbsolutePath().endsWith("\\\\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\\\")+srcDir.substring(3);//拼接后,使用新路径new一个File对象,如果不存在这个目录,则新建目录组File newFile = new File(destDir);if(!newFile.exists()){newFile.mkdirs();}}//递归调用copyDir(file,destFile);}}
}

对象流

对象的序列化与反序列化

在这里插入图片描述

  1. 自动生成序列化版本号

    package bean;import java.io.Serializable;public class Student implements Serializable {//IDEA 自动生成序列化版本号private static final long serialVersionUID = 4443644181403304807L;//java虚拟机看到Serializable接口之后,会自动生成一个序列化版本号//这里没有手动写出来,java虚拟机会默认提供这个序列化版本号//建议将序列化版本号手动写出来,不建议自动生成//private static final long serialVersionUID = 23L;//java虚拟机识别一个类的时候先通过类名,如果类名一致,再通过序列化版本号区分private int no;private String name;private  String email;//过了很久,Student这个类源代码改动了,源代码改动之后,需要重新编译,编译之后生成了全新的字节码文件//并且class文件再次运行的时候,java虚拟机生成的序列化版本号也会发生相应的改变private int age;public Student() {}public Student(int no, String name) {this.no = no;this.name = name;}public int getNo() {return no;}public void setNo(int no) {this.no = no;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "Student{" +"no=" + no +", name='" + name + '\\'' +'}';}
    }
    

    序列化

    package io;import bean.Student;import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectOutputStream;/*1、java.io.NotSerializableException不支持序列化的异常2、参与序列化和反序列化的对象,必须实现Serializable接口3、注意:通过源代码发现,Serializable接口只是一个标志接口:public interface Serializable{}这个接口当中什么代码都没有,那么它起到一个什么作用?起到一个标识的作用,标志的作用,java虚拟机看到这个类实现了这个接口,可能会对这个类进行特殊待遇Serializable这个标志接口是给java虚拟机参考的,java虚拟机看到这个接口之后,会为该类自动生成一个序列化版本号4、序列化版本号有什么用?Exception in thread "main" java.io.InvalidClassException:bean.Student; local class incompatible:stream classdesc serialVersionUID = 1784035741799759860,(现在)local class serialVersionUID = 507572570600860136(之前)JAVA语言中采用什么机制来区分类的?第一:首先通过类名进行比对,如果类名不一样,肯定不是同一个类第二:如果类名一样,再怎么进行类的区别?靠序列化版本号进行区分。小明写了一个类:java.bean.Student implements Serializable小红写了一个类:java.bean.Student implements Serializable不同的人编写了“类名一样”的类,但这两个类仅仅是类名相同,这个时候序列化版本号就起到作用了。对于java虚拟机来说,java虚拟机是可以区分开这两个类的,因为这两个类都实现了Serializable接口都有默认的序列化版本号,他们的序列化版本号不一样,所以区分开了(这是自动生成序列化版本号的好处)自动生成序列化版本号的坏处:这种自动生成的序列化版本号的缺点是:一旦代码确定之后,不能进行后续的修改,因为只要修改,必然会重新编译此时会生成全新的序列化版本号,这个时候java虚拟机会认为这是一个全新的类(这样就坏了)最终结论:凡是一个类实现了Serializable接口,建议给该类提供一个固定不变的序列化版本号这样,以后这个类即使代码修改了,但是版本号不变,java虚拟机还是会认为这是同一个类*/
    public class ObjectOutputStreamText01 {public static void main(String[] args) throws IOException {//创建java对象Student s = new Student(111,"张三");//序列化ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("students"));//序列化对象oos.writeObject(s);//刷新oos.flush();//关闭oos.close();}
    }
    

    反序列化

    package io;import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.ObjectInputStream;/*反序列化*/
    public class ObjectInputStreamText01 {public static void main(String[] args) throws IOException, ClassNotFoundException {ObjectInputStream ois = new ObjectInputStream(new FileInputStream("students"));//开始反序列化,读Object obj = ois.readObject();//反序列化回来是一个学生对象,所以会调用学生对象的toString方法System.out.println(obj);ois.close();}
    }
    
  2. transient关键字

    package bean;import java.io.Serializable;public class User implements Serializable {private int no;//transient关键字表示游离的,不参与序列化private transient String name;  //name不参与序列化操作@Overridepublic String toString() {return "User{" +"no=" + no +", name='" + name + '\\'' +'}';}public int getNo() {return no;}public void setNo(int no) {this.no = no;}public String getName() {return name;}public void setName(String name) {this.name = name;}public User() {}public User(int no, String name) {this.no = no;this.name = name;}
    }
    

    一次序列化多个对象

    package io;import bean.User;import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectOutputStream;
    import java.util.ArrayList;
    import java.util.List;/*一次序列化多个对象呢?可以,可以将对象放到集合当中,序列化集合提示:参与序列化的ArrayList集合以及集合中的元素User都需要实现java.io.Serializable接口*/
    public class ObjectOutputStreamText02 {public static void main(String[] args) throws IOException {List<User> userList = new ArrayList<>();userList.add(new User(121,"张三"));userList.add(new User(13,"三"));userList.add(new User(34,"打发士三"));ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("users"));//序列化一个集合,这个集合对象中放了很多其他对象oos.writeObject(userList);oos.flush();oos.close();}
    }
    

    反序列化集合

    package io;import bean.User;import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.util.List;/*反序列化集合*/
    public class ObjectInputStreamText02 {public static void main(String[] args) throws IOException, ClassNotFoundException {ObjectInputStream ois = new ObjectInputStream(new FileInputStream("users"));
    /*        Object obj = ois.readObject();System.out.println(obj instanceof List);*/List<User> userList = (List<User>)ois.readObject();for(User u : userList){System.out.println(u);}ois.close();}
    }
    
  3. IO+Properties的联合应用

    package io;import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Properties;/*IO+Properties的联合应用非常好的一个设计理念:以后经常改变的数据,可以单独写到一个文件中,使用程序动态读取。将来只要修改这个文件的内容,java代码不需要改动,不需要重新编译,服务器也不需要重启。就可以拿到动态的信息。类似于以上机制的这种文件被称为配置文件。并且当配置文件的内容格式是:key1 = valuekey2 = value的时候,我们把这种配置文件称为属性配置文件java规范中有要求:属性配置文件建议以.properties结尾,但这不是必须的。这种以.properties结尾的文件在java中被称为:属性配置文件。其中properties是专门存放属性配置文件内容的一个类。*/
    public class IoPropertiesText01 {public static void main(String[] args) throws IOException {/*Properties是一个Map集合,key和value都是String类型。想要将userinfo文件中的数据加载到Properties对象当中。*///创建一个输入流对象FileReader reader = new FileReader("io/userinfo.properties");//新建一个Map集合Properties pro = new Properties();//调用Properties对象的load方法将文件中的数据加载到Map集合中。pro.load(reader);//文件中的数据顺着管道加载到Map集合中,其中=左边做key,右边做value//通过key来获取value呢?String s = pro.getProperty("username");System.out.println(s);String ss = pro.getProperty("password");System.out.println(ss);String sss = pro.getProperty("data");System.out.println(sss);String ssss = pro.getProperty("usernamex");System.out.println(ssss);}
    }