zoukankan      html  css  js  c++  java
  • Java IO流

    Java IO流

    笔记

    1、集合这块最主要掌握什么内容?
    1.1、每个集合对象的创建(new)
    1.2、向集合中添加元素
    1.3、从集合中取出某个元素
    1.4、遍历集合
    1.5、主要的集合类:
    ArrayList
    LinkedList
    HashSet (HashMap的key,存储在HashMap集合key的元素需要同时重写hashCode + equals)
    TreeSet
    HashMap
    Properties
    TreeMap

    2、IO流,什么是IO?
    I : Input
    O : Output
    通过IO可以完成硬盘文件的读和写。

    3、IO流的分类?

    有多种分类方式:
    
    	一种方式是按照流的方向进行分类:
    		以内存作为参照物,
    			往内存中去,叫做输入(Input)。或者叫做读(Read)。
    			从内存中出来,叫做输出(Output)。或者叫做写(Write)。
    
    	另一种方式是按照读取数据方式不同进行分类:
    		有的流是按照字节的方式读取数据,一次读取1个字节byte,等同于一次读取8个二进制位。
    		这种流是万能的,什么类型的文件都可以读取。包括:文本文件,图片,声音文件,视频文件等....
    			假设文件file1.txt,采用字节流的话是这样读的:
    				a中国bc张三fe
    				第一次读:一个字节,正好读到'a'
    				第二次读:一个字节,正好读到'中'字符的一半。
    				第三次读:一个字节,正好读到'中'字符的另外一半。
    			扩展:'a'在Windows系统中是1个字节,在java中是两个字节,
    			那为什么第一次读:一个字节,正好读到'a',而不是'a'的一半呢?
    			因为file1是一个文件,在Windows系统上该文件的第一个字符是'a',那么java读入一个字节,在java中只要“类名”以Stream结尾的都是字节流。以“Reader/Writer”结尾的都是字符流。
    			该字符就变成了2个字节。所以读取字符是无需关心java内部存放占用多少字节,只需关心从外部读取多少字节。
    		有的流是按照字符的方式读取数据的,一次读取一个字符,这种流是为了方便读取
    		普通文本文件而存在的,这种流不能读取:图片、声音、视频等文件。只能读取纯
    		文本文件,连word文件都无法读取。
    			假设文件file1.txt,采用字符流的话是这样读的:
    				a中国bc张三fe
    				第一次读:'a'字符('a'字符在windows系统中占用1个字节。)
    				第二次读:'中'字符('中'字符在windows系统中占用2个字节。)
    
    综上所述:流的分类
    	输入流、输出流
    	字节流、字符流
    

    4、Java中的IO流都已经写好了,我们程序员不需要关心,我们最主要还是掌握,在java中已经提供了哪些流,每个流的特点是什么,每个流对象上的常用方法有哪些????

    >java中所有的流都是在:java.io.*;下。
    >
    >java中主要还是研究:
    >	怎么new流对象。
    >	调用流对象的哪个方法是读,哪个方法是写。
    

    5、java IO流这块有四大家族:

    四大家族的首领:
    	java.io.InputStream  字节输入流
    	java.io.OutputStream 字节输出流
    	java.io.Reader		字符输入流
    	java.io.Writer		字符输出流
    
    	四大家族的首领都是抽象类。(abstract class)
    
    	所有的流都实现了:
    		java.io.Closeable接口,都是可关闭的,都有close()方法。
    		流毕竟是一个管道,这个是内存和硬盘之间的通道,用完之后一定要关闭,
    		不然会耗费(占用)很多资源。养成好习惯,用完流一定要关闭。
    
    	所有的输出流都实现了:
    		java.io.Flushable接口,都是可刷新的,都有flush()方法。
    		养成一个好习惯,输出流在最终输出之后,一定要记得flush()
    		刷新一下。这个刷新表示将通道/管道当中剩余未输出的数据
    		强行输出完(清空管道!)刷新的作用就是清空管道。
    		注意:如果没有flush()可能会导致丢失数据。
    
    
    注意:在java中只要“类名”以Stream结尾的都是字节流。以“Reader/Writer”结尾的都是字符流。
    

    6、java.io包下需要掌握的流有16个【重点】:

    文件专属:
    	java.io.FileInputStream(掌握)
    	java.io.FileOutputStream(掌握)
    	java.io.FileReader
    	java.io.FileWriter
    
    转换流:(将字节流转换成字符流)
    	java.io.InputStreamReader
    	java.io.OutputStreamWriter
    
    缓冲流专属:
    	java.io.BufferedReader
    	java.io.BufferedWriter
    	java.io.BufferedInputStream
    	java.io.BufferedOutputStream
    
    数据流专属:
    	java.io.DataInputStream
    	java.io.DataOutputStream
    
    标准输出流:
    	java.io.PrintWriter
    	java.io.PrintStream(掌握)
    
    对象专属流:
    	java.io.ObjectInputStream(掌握)
    	java.io.ObjectOutputStream(掌握)
    

    7、java.io.File类。
    File类的常用方法。

    8、java io这块还剩下什么内容:
    第一:ObjectInputStream ObjectOutputStream的使用。
    第二:IO流+Properties集合的联合使用。

    文件流

    FileInputStreamTest01——文件输入流

    java.io.FileInputStream:
    1、文件字节输入流,万能的,任何类型的文件都可以采用这个流来读。
    2、字节的方式,完成输入的操作,完成读的操作(硬盘---> 内存)

    使用文件输入流读取文件:

    FileInputStream fis = new FileInputStream(String name),该文件通过文件系统中的路径名 name 指定。

    int read():从此输入流中读取一个字节,返回值是下一个数据字节;如果已到达文件末尾,则返回 -1.

    关于路径名name:

    以下是对于IDEA工具来说:

    1. 可以是绝对路径,如:G:StudyJavachapter23 emp01.txt

    2. 可以是相对路径,相对于你的Project的路径。

    在Project的根路径下:temp01.txt

    在Project/Module/temp01.txt文件:chapter23/temp01.txt chapter23表示的模块名。

    在Project/Module/src/temp01.txt:chapter23/src/temp01.txt

    在Project/Module/src/package/temp01.txt:chapter23/src/io/temp01.txt

    读取原理:

    image-20200914160304183

    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    public class FileInputStreamTest01 {
        public static void main(String[] args) {
            FileInputStream fis = null;
            try {
                // 创建文件字节输入流对象
                // 文件路径:IDEA会自动把编程\,因为java中表示转义)
                // 以下都是采用了:绝对路径的方式。
                //FileInputStream fis = new FileInputStream("D:\course\JavaProjects\02-JavaSE\temp");
                // 写成这个/也是可以的。
                fis = new FileInputStream("D:/course/JavaProjects/02-JavaSE/temp");
    
                // 开始读
                int readData = fis.read(); // 这个方法的返回值是:读取到的“字节”本身。
                System.out.println(readData); //97
    
                readData = fis.read();
                System.out.println(readData); //98
    
                readData = fis.read();
                System.out.println(readData); //99
    
                readData = fis.read();
                System.out.println(readData); //100
    
                readData = fis.read();
                System.out.println(readData); //101
    
                readData = fis.read();
                System.out.println(readData); //102
    
                // 已经读到文件的末尾了,再读的时候读取不到任何数据,返回-1.
                readData = fis.read();
                System.out.println(readData);
    
                readData = fis.read();
                System.out.println(readData);
    
                readData = fis.read();
                System.out.println(readData);
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 在finally语句块当中确保流一定关闭。
                if (fis != null) { // 避免空指针异常!
                    // 关闭流的前提是:流不是空。流是null的时候没必要关闭。
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    

    FileInputStreamTest02——对第一个程序进行改进,使用循环方式

    第一次改进:使用while循环

    while(true) {
        int readData = fis.read();
        if(readData == -1) {
            break;
        }
        System.out.println(readData);
    }
    

    第二次改进:对while循环进行改进

    int readData = 0;
    while((readData = fis.read()) != -1){
        System.out.println(readData);
    }
    

    仍然存在的缺点:

    一次读取一个字节byte,这样内存和硬盘交互太频繁,基本上时间/资源都耗费在交互上面了。

    public class FileInputStreamTest02 {
        public static void main(String[] args) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream("D:\course\JavaProjects\02-JavaSE\temp");
    			//使用while循环
                /*while(true) {
                    int readData = fis.read();
                    if(readData == -1) {
                        break;
                    }
                    System.out.println(readData);
                }*/
    
                // 改造while循环
                int readData = 0;
                while((readData = fis.read()) != -1){
                    System.out.println(readData);
                }
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    

    FileInputStreamTest03——使用字节数组缓冲区

    引入字节数组缓冲区:

    1、int read()方法每次只读取一个字节,硬盘与内存的交互比较频繁。因此,为了减少硬盘和内存的交互,提高程序的执行效率,引入字节数组缓冲区,每次读取到一定字节数再进行交互。

    2、int read(byte[] b) 方法每次将最多 b.length 个字节的数据读入一个 byte 数组中,大大减少了减少硬盘和内存的交互次数,该方法的返回值是:读取到的字节数量(不是字节本身)。

    3、字节数组缓存区的原理:

    image-20200914174656979

    public class FileInputStreamTest03 {
        public static void main(String[] args) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream("chapter23/src/com/exaple/java/io/tempfile4");
    
                // 开始读,采用byte数组,一次读取多个字节。最多读取“数组.length”个字节。
                byte[] bytes = new byte[4]; // 准备一个4个长度的byte数组,一次最多读取4个字节。
                // 这个方法的返回值是:读取到的字节数量。(不是字节本身)
                int readCount = fis.read(bytes);
                System.out.println(readCount); // 第一次读到了4个字节。
                // 将字节数组全部转换成字符串
                System.out.println(new String(bytes)); // abcd
                // 不应该全部都转换,应该是读取了多少个字节,转换多少个。
                System.out.println(new String(bytes,0, readCount));
    
                readCount = fis.read(bytes); // 第二次只能读取到2个字节。
                System.out.println(readCount); // 2
                // 将字节数组全部转换成字符串
                //System.out.println(new String(bytes)); // efcd
                // 不应该全部都转换,应该是读取了多少个字节,转换多少个。
                System.out.println(new String(bytes,0, readCount));
    
                readCount = fis.read(bytes); // 1个字节都没有读取到返回-1
                System.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();
                    }
                }
            }
        }
    }
    

    FileInputStreamTest04——最终版,需要掌握。

    int readCount = 0;
    while((readCount = fis.read(bytes)) != -1) {
        System.out.print(new String(bytes, 0, readCount));
    }
    
    package com.bjpowernode.java.io;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    /*
    最终版,需要掌握。
     */
    public class FileInputStreamTest04 {
        public static void main(String[] args) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream("chapter23/src/tempfile3");
                // 准备一个byte数组
                byte[] bytes = new byte[4];
                /*while(true){
                    int readCount = fis.read(bytes);
                    if(readCount == -1){
                        break;
                    }
                    // 把byte数组转换成字符串,读到多少个转换多少个。
                    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();
                    }
                }
            }
        }
    }
    

    FileInputStreamTest05——FileInputStream类的available()和skip()方法

    int available():返回流当中剩余的没有读到的字节数量。

    available()方法的使用场景是什么?

    在读取文件时,可以创建一个指定大小的缓冲区,使得一次性读取完所以字节。

    byte[] bytes = new byte[fis.available()];

    缺点:这种方式不太适合太大的文件,因为byte[]数组不能太大。

    long skip():从输入流中跳过并丢弃 n 个字节的数据。

    skip()这个方法的使用场景是什么?

    如在所要读取的文件中每个多少个字节,会有一段不需要的字节内容,那么在每次读取字节到缓冲区之后,可使用skip() 跳过,不去读取那一部分不需要的字节内容。

    /*
    FileInputStream类的其它常用方法:
        int available():返回流当中剩余的没有读到的字节数量
        long skip(long n):跳过几个字节不读。
     */
    public class FileInputStreamTest05 {
        public static void main(String[] args) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream("tempfile");
                System.out.println("总字节数量:" + fis.available());
                // 读1个字节
                //int readByte = fis.read();
                // 还剩下可以读的字节数量是:5
                //System.out.println("剩下多少个字节没有读:" + fis.available());
                // 这个方法有什么用?
                //byte[] bytes = new byte[fis.available()]; // 这种方式不太适合太大的文件,因为byte[]数组不能太大。
                // 不需要循环了。
                // 直接读一次就行了。
                //int readCount = fis.read(bytes); // 6
                //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();
                    }
                }
            }
        }
    }
    

    FileOutputStream文件输出流

    FileOutputStream的构造方法:

    1. FileOutputStream(String name):创建一个向具有指定名称的文件中写入数据的输出文件流。

    name:输出的文件路径,可以是绝对路径,也可以是相对路径。

    1. FileOutputStream(String name,boolean append):以追加的方式写到文件中,不会清空原文件的内容。

    append:true表示以追加的方式写到文件中。

    1. FileOutputStream(File file):创建一个向指定 File 对象表示的文件中写入数据的文件输出流。

    FileOutputStream的常用方法:

    1. void close():关闭输出流,释放与此流有关的所有系统资源。(必须)
    2. void write(byte[] b):将字节数组中的内容写出。
    3. void write(byte[] b,int off,int len):将字节数组中一部分内容写出。

    示例1:向autoGenerateFile.txt文件中写入内容"abcd"。

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream("chapter23/autoGenerateFile.txt");
        //指定要写到文件中的内容
        byte[] bytes = {97, 98, 99, 100};	//abcd
        //将byte数组全部写出!
        fos.write(bytes);
        //将byte数组的一部分写出!
        fos.write(bytes,0,2);   //ab
        //写完之后,最后一定要刷新
        fos.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    说明:

    • 文件不存在的时候会自动新建!
    • 这种构造方法应该谨慎使用,因为会先将原文件清空,然后重新写入。
    • 最后一定要将输出流对象关闭,释放系统资源。

    示例2:向autoGenerateFile.txt文件中追加内容"我是一个中国人,我骄傲!!!"。

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream("chapter23/autoGenerateFile.txt",true);
        //定义要输出的内容1
        byte[] bytes = {97, 98, 99, 100};
        fos.write(bytes);
        //指定要输出的内容2
        String s = "我是一个中国人,我骄傲!!!";
        //转化为字节数组
        byte[] bytes1 = s.getBytes();
       	//写出
        fos.write(bytes1);
        //刷新
        fos.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    Copy01——使用FileInputStream + FileOutputStream完成文件的拷贝

    复制文件原理:

    使用FileInputStream + FileOutputStream完成文件的拷贝。

    拷贝的过程应该是一边读,一边写。

    使用以上的字节流拷贝文件的时候,文件类型随意,万能的。什么样的文件都能拷贝。

    public class Copy01 {
        public static void main(String[] args) {
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                // 创建一个输入流对象
                fis = new FileInputStream("D:\course\02-JavaSE\video\chapter01\动力节点-JavaSE-杜聚宾-001-文件扩展名的显示.avi");
                // 创建一个输出流对象
                fos = new FileOutputStream("C:\动力节点-JavaSE-杜聚宾-001-文件扩展名的显示.avi");
    
                // 最核心的:一边读,一边写
                byte[] bytes = new byte[1024 * 1024]; // 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();
                    }
                }
            }
        }
    }
    

    FileReader的用法

    FileReader的构造方法:

    1. FileReader(String fileName):在给定文件名的文本文件中读取数据。
    2. FileReader(File file):在给定 File中读取数据。

    FileReader的常用方法:

    1. void close():关闭该流并释放与之关联的所有资源。
    2. int read():读取单个字符。
    3. int read(char[] cbuf):将字符读入数组。返回值是读取的字符数,如果已到达流的末尾,则返回 -1 。
    4. int read(char[] cbuf,int off,int len):将字符读入数组的某一部分。
    5. long skip(long n):跳过字符。参数n 要跳过的字符数 ,返回值是实际跳过的字符数 。

    FileReader读取文件的特点:

    文件字符输入流,只能读取普通文本。
    读取文本内容时,比较方便,快捷。

    public class FileReaderTest {
        public static void main(String[] args) {
            FileReader reader = null;
            try {
                // 创建文件字符输入流
                reader = new FileReader("tempfile");
             	// 开始读
                char[] chars = new char[4]; // 一次读取4个字符
                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 {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    

    FileWriter的用法

    FileWriter特点:

    文件字符输出流。写。
    只能输出普通文本。

    public class FileWriterTest {
        public static void main(String[] args) {
            FileWriter out = null;
            try {
                // 创建文件字符输出流对象
                //out = new FileWriter("file");
                out = new FileWriter("file", true);
    
                // 开始写。
                char[] chars = {'我','是','中','国','人'};
                out.write(chars);
                out.write(chars, 2, 3);
    
                out.write("我是一名java软件工程师!");
                // 写出一个换行符。
                out.write("
    ");
                out.write("hello world!");
    
                // 刷新
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    

    Copy02——使用FileReader、FileWriter进行拷贝“普通文本”文件。

    步骤:

    1. 创建FileReader对象、FileWriter对象,指定读入和写入文件的路径。
    2. 创建缓冲区大小。
    3. 一边读一边写
    4. flush刷新。
    5. 关闭流对象。
    public class Copy02 {
        public static void main(String[] args) {
            FileReader in = null;
            FileWriter out = null;
            try {
                // 读
                in = new FileReader("chapter23/src/com/bjpowernode/java/io/Copy02.java");
                // 写
                out = new FileWriter("Copy02.java");
    
                // 一边读一边写:
                char[] chars = new char[1024 * 512]; // 1MB
                int 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();
                    }
                }
            }
    
        }
    }
    

    缓冲流

    BufferedReader——带有缓冲区的字符输入流

    BufferedReader:

    带有缓冲区的字符输入流。
    使用这个流的时候不需要自定义char数组,或者说不需要自定义byte数组。自带缓冲。

    BufferedReader构造方法:

    1. BufferedReader(Reader in):创建一个使用默认大小输入缓冲区的缓冲字符输入流。

      需要传入的对象是:Reader类型的,但Reader是抽象类型的,因此使用其子类FileReader。

      注意FileReader reader = new FileReader("Copy02.java");创建完Reader对象之后不需要关闭这个流。

      只需关闭最外层的包装流/处理流即可。

    2. BufferedReader(Reader in,int sz):创建一个使用指定大小输入缓冲区的缓冲字符输入流。 (不常用)

    BufferedReader的一个特殊的方法:

    String readLine():读取一个文本行。通过下列字符之一即可认为某行已终止:换行 (' ')、回车 (' ') 或回车后直接跟着换行。

    注意读取之后的行与行之间是没有换行符的。

    image-20200914214415645

    流的分类:

    FileReader reader = new FileReader("Copy02.java");
    当一个流的构造方法中需要一个流的时候,这个被传进来的流叫做:节点流
    外部负责包装的这个流,叫做:包装流/处理流
    像当前这个程序来说:FileReader就是一个节点流。BufferedReader就是包装流/处理流。
    BufferedReader br = new BufferedReader(reader);

    包装流和节点流是相对的【套娃原理】。

    public class BufferedReaderTest01 {
        public static void main(String[] args) throws Exception{
    
            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 line3 = br.readLine();
            System.out.println(line3);*/
    
            // br.readLine()方法读取一个文本行,但不带换行符。
            String s = null;
            while((s = br.readLine()) != null){
                System.out.print(s);
            }
    
            // 关闭流
            // 对于包装流来说,只需要关闭最外层流就行,里面的节点流会自动关闭。(可以看源代码。)
            br.close();
        }
    }
    

    BufferedWriter——带有缓冲的字符输出流

    /*
    BufferedWriter:带有缓冲的字符输出流。
    OutputStreamWriter:转换流
     */
    public class BufferedWriterTest {
        public static void main(String[] args) throws Exception{
            // 带有缓冲区的字符输出流
            //BufferedWriter out = new BufferedWriter(new FileWriter("copy"));
    
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("copy", true)));
            // 开始写。
            out.write("hello world!");
            out.write("
    ");
            out.write("hello kitty!");
            // 刷新
            out.flush();
            // 关闭最外层
            out.close();
        }
    }
    

    转换流

    InputStreamReader——将InputStream流转换为Reader类型的流

    如果只有FileInputStream文件输入流,怎么使用BufferedReader字符缓冲流?

    1. 获取FileInputStream文件输入流: FileInputStream in = new FileInputStream("Copy02.java");
    2. 获取InputStreamReader 转换流: InputStreamReader reader = new InputStreamReader(in);
    3. 获取BufferedReader 字符缓冲流: BufferedReader br = new BufferedReader(reader);

    关闭流时,只需关闭最外层即可,因为包装流内部已经封装了关闭节点流的方法。

    类似于俄罗斯套娃。。。

    /*
        转换流:InputStreamReader
     */
    public class BufferedReaderTest02 {
        public static void main(String[] args) throws Exception{
    
            /*// 字节流
            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();
        }
    }
    

    数据流

    DataInputStreamTest01——数据字节输入流

    /*
    DataInputStream:数据字节输入流。
    DataOutputStream写的文件,只能使用DataInputStream去读。并且读的时候你需要提前知道写入的顺序。
    读的顺序需要和写的顺序一致。才可以正常取出数据。
    
     */
    public class DataInputStreamTest01 {
        public static void main(String[] args) throws Exception{
            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 c = dis.readChar();
    
            System.out.println(b);
            System.out.println(s);
            System.out.println(i + 1000);
            System.out.println(l);
            System.out.println(f);
            System.out.println(d);
            System.out.println(sex);
            System.out.println(c);
    
            dis.close();
        }
    }
    

    DataOutputStreamTest——数据专属输出流

    package com.bjpowernode.java.io;
    
    import java.io.DataOutputStream;
    import java.io.FileOutputStream;
    
    /*
    java.io.DataOutputStream:数据专属的流。
    这个流可以将数据连同数据的类型一并写入文件。
    注意:这个文件不是普通文本文档。(这个文件使用记事本打不开。)
     */
    public class DataOutputStreamTest {
        public static void main(String[] args) throws Exception{
            // 创建数据专属的字节输出流
            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 = false;
            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();
        }
    }
    

    打印流

    PrintStream——标准的字节输出流,默认输出到控制台

    1、常用的打印输出到控制台:System.out.println("hello world!");

    2、分开写法:

    PrintStream ps = System.out;
    ps.println("hello world!");

    3、标准输出流不需要手动close()关闭

    4、可以改变标准输出流的输出方向:System.setOut(printStream);,当改变输出流的方向时,System.out.println("hello world");就不是在控制台打印输出了。

    5、PrintStream的构造方法:

    PrintStream(OutputStream out):参数为OutputStream 类型的。

    // 标准输出流不再指向控制台,指向“log”文件。
    PrintStream printStream = new PrintStream(new FileOutputStream("log"));

    // 修改输出方向,将输出方向修改到"log"文件。
    System.setOut(printStream);
    // 再输出
    System.out.println("hello world");

    /*
    java.io.PrintStream:标准的字节输出流。默认输出到控制台。
     */
    public class PrintStreamTest {
        public static void main(String[] args) throws Exception{
    
            // 联合起来写
            System.out.println("hello world!");
    
            // 分开写
            PrintStream ps = System.out;
            ps.println("hello zhangsan");
            ps.println("hello lisi");
            ps.println("hello wangwu");
    
            // 标准输出流不需要手动close()关闭。
            // 可以改变标准输出流的输出方向吗? 可以
            /*
            // 这些是之前System类使用过的方法和属性。
            System.gc();
            System.currentTimeMillis();
            PrintStream ps2 = System.out;
            System.exit(0);
            System.arraycopy(....);
             */
    
            // 标准输出流不再指向控制台,指向“log”文件。
            PrintStream printStream = new PrintStream(new FileOutputStream("log"));
            // 修改输出方向,将输出方向修改到"log"文件。
            System.setOut(printStream);
            // 再输出
            System.out.println("hello world");
            System.out.println("hello kitty");
            System.out.println("hello zhangsan");
        }
    }
    

    使用PrintStream完成简单的生成日志文件功能

    步骤:

    1. 创建PrintStream输出流对象,指定输出文件的路径。

      PrintStream out = new PrintStream(new FileOutputStream("log.txt", true));

    2. 改变输出方向。

      System.setOut(out);

    3. 输出内容。

      System.out.println(strTime + ": " + msg);

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

    File类

    FileTest01——File类常用方法

    1. File类和四大家族【InputStream、OutputStream、Reader、Writer】的关系?

      File类和四大家族没有关系,所以File类不能完成文件的读和写。

    2. File对象代表什么?

      文件和目录路径名的抽象表示形式。

      C:Drivers 这是一个File对象
      C:DriversLanRealtekReadme.txt 也是File对象。
      一个File对象有可能对应的是目录,也可能是文件。
      File只是一个路径名的抽象表示形式。

    3. File类中常用的方法

      • public File(String pathname):通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例。

        // 创建一个File对象
        File f1 = new File("D:file");

      • boolean exists():判断文件或目录是否存在。

        file.exists()

        true:表示目录或者文件存在。

        false:表示目录或者文件不存在。

      • boolean createNewFile():如果指定的文件不存在并成功地创建,则返回 true;如果指定的文件已经存在,则返回 false .

        //文件不存在

        if(!file.exists()) {
        // 以文件形式新建
        file.createNewFile();

        }

      • boolean mkdir():创建目录,创建成功,返回 true;否则返回 false 。

        //目录不存在

        if(!file.exists()) {
        // 以目录形式新建
        file.mkdir();

        }

      • boolean mkdirs():创建多重目录,中间不存在的目录也会创建。

        File f2 = new File("D:/a/b/c/d/e/f");
        if(!f2.exists()) {
        // 多重目录的形式新建。
        f2.mkdirs();
        }

      • String getParent():返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回 null。

        File f3 = new File("D:course1-开课学习方法.txt");
        // 获取文件的父路径
        String parentPath = f3.getParent();
        System.out.println(parentPath); //D:course1-开课

      • File getParentFile():返回值是一个父目录的File对象。

      • String getPath():将此抽象路径名转换为一个路径名字符串。

        File file2 = new File("chapter23/copy02.txt");
        String path = file2.getPath(); //chapter23copy02.txt

      • String getAbsolutePath():返回此抽象路径名的绝对路径名字符串。

        File file2 = new File("chapter23/copy02.txt");

        //绝对路径
        String file2AbsolutePath = file2.getAbsolutePath();
        System.out.println(file2AbsolutePath); //G:StudyJavachapter23copy02.txt

    public class FileTest01 {
        public static void main(String[] args) throws Exception {
            // 创建一个File对象
            File f1 = new File("D:\file");
    
            // 判断是否存在!
            System.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:\course\01-开课\学习方法.txt");
            // 获取文件的父路径
            String parentPath = f3.getParent();
            System.out.println(parentPath); //D:course1-开课
            File parentFile = f3.getParentFile();
            System.out.println("获取绝对路径:" + parentFile.getAbsolutePath());
    
            File f4 = new File("copy");
            System.out.println("绝对路径:" + f4.getAbsolutePath()); // C:UsersAdministratorIdeaProjectsjavasecopy
        }
    }
    

    FileTest02——File类的常用方法

    • String getName():返回由此抽象路径名表示的文件或目录的名称该名称是路径名名称序列中的最后一个名称。如果路径名名称序列为空,则返回空字符串。

      //返回的是文件名称

      File file = new File("G:StudyJavachapter23copy02.txt");
      String name = file.getName();
      System.out.println(name); //copy02.txt

      //返回的是最后一个文件夹的名称

      File file2 = new File("G:StudyJavachapter23");
      String name2 = file2.getName();
      System.out.println(name2); //chapter23

    • boolean isDirectory():测试此抽象路径名表示的文件是否是一个目录。

      File file = new File("G:StudyJavachapter23copy02.txt");
      System.out.println(file.isFile()); //true
      System.out.println(file.isDirectory()); //false

      File file2 = new File("G:StudyJavachapter23");
      System.out.println(file2.isFile()); //false
      System.out.println(file2.isDirectory()); //true

    • boolean isFile():测试此抽象路径名表示的文件是否是一个标准文件。

    • long lastModified():返回此抽象路径名表示的文件最后一次被修改的时间,返回值是与时间点(1970 年 1 月 1 日,00:00:00 GMT)之间的毫秒数。

      File file = new File("G:StudyJavachapter23copy02.txt");
      //获得最后一次修改的时间
      long lastModified = file.lastModified();
      //格式化日期
      Date date = new Date(lastModified);
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
      String lastModifiedTime = sdf.format(date);
      System.out.println(lastModifiedTime); //2020-09-14 21:11:26 367

    • long length():返回由此抽象路径名表示的文件的长度。以字节为单位;如果文件不存在,则返回 0L。如果此路径名表示一个目录,则返回值是不确定的。

      File file = new File("G:StudyJavachapter23copy02.txt");
      long length = file.length();
      System.out.println(length); //1409字节,1.37kb

    • boolean renameTo(File dest):重新命名此抽象路径名表示的文件。 参数是指定文件的新抽象路径名 ,当且仅当重命名成功时,返回 true;否则返回 false 。

      File file3 = new File("G:StudyJavachapter23 est02.txt");
      // 给file3重命名
      boolean b = file3.renameTo(new File("chapter23/hahah.txt"));
      System.out.println(b?"重命名成功":"重命名失败");

    • boolean setLastModified(long time):设置此抽象路径名指定的文件或目录的最后一次修改时间。

      //设置最后的修改时间
      File file4 = new File("chapter23/hahah.txt");
      long modified = file4.lastModified();
      SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
      String s = sdf1.format(modified);
      System.out.println(file4.getName() + "的最后修改为:" + s);
      boolean b = file4.setLastModified(System.currentTimeMillis()); //设置最后修改时间为当前时间。

    public class FileTest02 {
        public static void main(String[] args) {
    
            File f1 = new File("D:\course\01-开课\开学典礼.ppt");
            // 获取文件名
            System.out.println("文件名:" + f1.getName());
    
            // 判断是否是一个目录
            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()); //216064字节。
        }
    }
    

    FileTest03——File类的常用方法

    • String[] list():返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件和目录。

      File file = new File("D:Drivers");
      String[] list = file.list();
      //返回的是该目录下所有的文件夹和文件的名称,相比较来说,下面这一种方法更为常用。

    • File[] listFiles():返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。

      拿到的是该目录下所有的文件或文件夹对象,实用性更强,比如整个文件夹的拷贝。

    package com.bjpowernode.java.io;
    
    import java.io.File;
    
    /*
    File中的listFiles方法。
     */
    public class FileTest03 {
        public static void main(String[] args) {
            // File[] listFiles()
            // 获取当前目录下所有的子文件。
            File f = new File("D:\course\01-开课");
            File[] files = f.listFiles();
            // foreach
            for(File file : files){
                //System.out.println(file.getAbsolutePath());
                System.out.println(file.getName());
            }
        }
    }
    

    拷贝目录【难点】

    使用到的知识点:File、FileInputStream、FileOutputStream、递归算法。

    讲解:https://www.bilibili.com/video/BV1mE411x7Wt?p=272

    package com.bjpowernode.java.io;
    
    import java.io.*;
    
    /*
    拷贝目录
     */
    public class CopyAll {
        public static void main(String[] args) {
            // 拷贝源
            File srcFile = new File("D:\course\02-JavaSE\document");
            // 拷贝目标
            File destFile = new File("C:\a\b\c");
            // 调用方法拷贝
            copyDir(srcFile, destFile);
        }
    
        /**
         * 拷贝目录
         * @param srcFile 拷贝源
         * @param destFile 拷贝目标
         */
        private static void copyDir(File srcFile, File destFile) {
            if(srcFile.isFile()) {
                // srcFile如果是一个文件的话,递归结束。
                // 是文件的时候需要拷贝。
                // ....一边读一边写。
                FileInputStream in = null;
                FileOutputStream out = null;
                try {
                    // 读这个文件
                    // D:course2-JavaSEdocumentJavaSE进阶讲义JavaSE进阶-01-面向对象.pdf
                    in = new FileInputStream(srcFile);
                    // 写到这个文件中
                    // C:course2-JavaSEdocumentJavaSE进阶讲义JavaSE进阶-01-面向对象.pdf
                    String path = (destFile.getAbsolutePath().endsWith("\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\")  + srcFile.getAbsolutePath().substring(3);
                    out = new FileOutputStream(path);
                    // 一边读一边写
                    byte[] bytes = new byte[1024 * 1024]; // 一次复制1MB
                    int readCount = 0;
                    while((readCount = in.read(bytes)) != -1){
                        out.write(bytes, 0, readCount);
                    }
                    out.flush();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                return;
            }
            // 获取源下面的子目录
            File[] files = srcFile.listFiles();
            for(File file : files){
                // 获取所有文件的(包括目录和文件)绝对路径
                //System.out.println(file.getAbsolutePath());
                if(file.isDirectory()){
                    // 新建对应的目录
                    //System.out.println(file.getAbsolutePath());
                    //D:course2-JavaSEdocumentJavaSE进阶讲义       源目录
                    //C:course2-JavaSEdocumentJavaSE进阶讲义       目标目录
                    String srcDir = file.getAbsolutePath();
                    String destDir = (destFile.getAbsolutePath().endsWith("\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\")  + srcDir.substring(3);
                    File newFile = new File(destDir);
                    if(!newFile.exists()){
                        newFile.mkdirs();
                    }
                }
                // 递归调用
                copyDir(file, destFile);
            }
        }
    }
    

    对象流

    ObjectOutputStreamTest01——序列化

    1. 参与序列化和反序列化的对象,必须实现Serializable接口。

      否者会出现异常:java.io.NotSerializableException,Student对象不支持序列化!!!!

    2. 通过源代码发现,Serializable接口只是一个标志接口:

      public interface Serializable {
      }

      这个接口当中什么代码都没有,那么它起到一个什么作用呢?
      起到标识的作用,标志的作用,java虚拟机看到这个类实现了这个接口,可能会对这个类进行特殊待遇。
      Serializable这个标志接口是给java虚拟机参考的,java虚拟机看到这个接口之后,会为该类自动生成一个序列化版本号。

    3. 序列化版本号有什么用呢?

      如果没有指定序列化版本号,即采用随机的序列化版本号,那么当修改实体类对象时,那么序列化后的文件就不能通过反序列化读取到了,会报如下异常:

      java.io.InvalidClassException:
      com.bjpowernode.java.bean.Student;
      local class incompatible:
      stream classdesc serialVersionUID = -684255398724514298(十年后),
      local class serialVersionUID = -3463447116624555755(十年前)

      修改之前,在本地已经序列化的对象的 serialVersionUID = -3463447116624555755(十年前)

      修改之后,该实体类的序列化版本号 serialVersionUID = -684255398724514298(十年后)

      当进行反序列化时,两个序列化版本不一样,就会被认为是不同的类,因此也就无法按照10年后的代码取出10年前的对象。

    4. java语言中是采用什么机制来区分类的?

      第一:首先通过类名进行比对,如果类名不一样,肯定不是同一个类。
      第二:如果类名一样,再怎么进行类的区别?靠序列化版本号进行区分。

      如:

      ​ 小鹏编写了一个类:com.bjpowernode.java.bean.Student implements Serializable
      ​ 胡浪编写了一个类:com.bjpowernode.java.bean.Student implements Serializable
      ​ 不同的人编写了同一个类,但“这两个类确实不是同一个类”。这个时候序列化版本就起上作用了。
      ​ 对于java虚拟机来说,java虚拟机是可以区分开这两个类的,因为这两个类都实现了Serializable接口,
      ​ 都有默认的序列化版本号,他们的序列化版本号不一样。所以区分开了。(这是自动生成序列化版本号的好处)

    5. 这种自动生成序列化版本号有什么缺陷?

      这种自动生成的序列化版本号缺点是:一旦代码确定之后,不能进行后续的修改,
      因为只要修改,必然会重新编译,此时会生成全新的序列化版本号,这个时候java
      虚拟机会认为这是一个全新的类。(这样就不好了!)

    6. 最终结论

      凡是一个类实现了Serializable接口,建议给该类提供一个固定不变的序列化版本号。
      这样,以后这个类即使代码修改了,但是版本号不变,java虚拟机会认为是同一个类。

    7. 对象的序列化和反序列化。

      day32-对象的序列化和反序列化

    public class ObjectOutputStreamTest01 {
        public static void main(String[] args) throws Exception{
            // 创建java对象
            Student s = new Student(1111, "zhangsan");
            // 序列化
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("students"));
    
            // 序列化对象
            oos.writeObject(s);
    
            // 刷新
            oos.flush();
            // 关闭
            oos.close();
        }
    }
    

    ObjectInputStreamTest01——反序列化

    public class ObjectInputStreamTest01 {
        public static void main(String[] args) throws Exception{
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("students"));
            // 开始反序列化,读
            Object obj = ois.readObject();
            // 反序列化回来是一个学生对象,所以会调用学生对象的toString方法。
            System.out.println(obj);
            ois.close();
        }
    }
    

    参与序列化和反序列化的对象Student:

    注意:

    1. 没有手动写出来序列化版本号,java虚拟机会默认提供这个序列化版本号。

      缺点就是一旦修改了这个类,序列化版本号可能就发生了改变,就不能在通过修改后的类获得已经序列化的对象了。

    2. 建议将序列化版本号手动的写出来。不建议自动生成。

    3. java虚拟机识别一个类的时候先通过类名,如果类名一致,再通过序列化版本号。

    public class Student implements Serializable {
    
        // IDEA工具自动生成序列化版本号。
        //private static final long serialVersionUID = -7998917368642754840L;
    
        // Java虚拟机看到Serializable接口之后,会自动生成一个序列化版本号。
        // 这里没有手动写出来,java虚拟机会默认提供这个序列化版本号。
        // 建议将序列化版本号手动的写出来。不建议自动生成
        private static final long serialVersionUID = 1L; // java虚拟机识别一个类的时候先通过类名,如果类名一致,再通过序列化版本号。
    
        private int no;
        //private String name;
    
        // 过了很久,Student这个类源代码改动了。
        // 源代码改动之后,需要重新编译,编译之后生成了全新的字节码文件。
        // 并且class文件再次运行的时候,java虚拟机生成的序列化版本号也会发生相应的改变。
        private int age;
        private String email;
        private String address;
    
        //无参构造、有参构造
        //Getter、Setter方法
        //toString方法
    }
    

    ObjectOutputStreamTest02——序列化多个对象

    序列化多个对象,实际上就是将多个对象放到 list 集合中,然后序列化该集合对象。

    注意:参与序列化的ArrayList集合以及集合中的元素User都需要实现 java.io.Serializable接口。

    public class ObjectOutputStreamTest02 {
        public static void main(String[] args) throws Exception{
            List<User> userList = new ArrayList<>();
            userList.add(new User(1,"zhangsan"));
            userList.add(new User(2, "lisi"));
            userList.add(new User(3, "wangwu"));
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("users"));
    
            // 序列化一个集合,这个集合对象中放了很多其他对象。
            oos.writeObject(userList);
    
            oos.flush();
            oos.close();
        }
    }
    

    ObjectInputStreamTest02——反序列化多个对象

    /*
    反序列化集合
     */
    public class ObjectInputStreamTest02 {
        public static void main(String[] args) throws Exception{
            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 user : userList){
                System.out.println(user);
            }
            ois.close();
        }
    }
    

    参与序列化和反序列化的对象User:

    transient关键字表示游离的,不参与序列化。那么在反序列化的时候该属性的值为null。

    public class User implements Serializable {
        private int no;
        // transient关键字表示游离的,不参与序列化。
        private transient String name; // name不参与序列化操作!
        //无参构造、有参构造
        //Getter、Setter方法
        //toString方法
    

    IO+Properties的联合应用

    读取Properties配置文件的步骤:

    1. 创建Reader对象:使用其实现类FileReader

      FileReader reader = new FileReader("chapter23/db.properties");

    2. 创建Properties对象。

      Properties pro = new Properties();

    3. 调用Properties对象的load方法将文件中的数据加载到Map集合中。

      pro.load(reader);

    4. 读取配置文件中的内容。

      String username = pro.getProperty("username");

    /*
    IO+Properties的联合应用。
    非常好的一个设计理念:
        以后经常改变的数据,可以单独写到一个文件中,使用程序动态读取。
        将来只需要修改这个文件的内容,java代码不需要改动,不需要重新
        编译,服务器也不需要重启。就可以拿到动态的信息。
    
        类似于以上机制的这种文件被称为配置文件。
        并且当配置文件中的内容格式是:
            key1=value
            key2=value
        的时候,我们把这种配置文件叫做属性配置文件。
    
        java规范中有要求:属性配置文件建议以.properties结尾,但这不是必须的。
        这种以.properties结尾的文件在java中被称为:属性配置文件。
        其中Properties是专门存放属性配置文件内容的一个类。
     */
    public class IoPropertiesTest01 {
        public static void main(String[] args) throws Exception{
            /*
            Properties是一个Map集合,key和value都是String类型。
            想将userinfo文件中的数据加载到Properties对象当中。
             */
            // 新建一个输入流对象
            FileReader reader = new FileReader("chapter23/userinfo.properties");
    
            // 新建一个Map集合
            Properties pro = new Properties();
    
            // 调用Properties对象的load方法将文件中的数据加载到Map集合中。
            pro.load(reader); // 文件中的数据顺着管道加载到Map集合中,其中等号=左边做key,右边做value
    
            // 通过key来获取value呢?
            String username = pro.getProperty("username");
            System.out.println(username);
    
            String password = pro.getProperty("password");
            System.out.println(password);
    
            String data = pro.getProperty("data");
            System.out.println(data);
    
            String usernamex = pro.getProperty("usernamex");
            System.out.println(usernamex);
        }
    }
    
  • 相关阅读:
    手机web页面调用手机QQ实现在线聊天的效果
    Java EE 6 最终草案暗示了平台的未来发展方向
    NetBeans 时事通讯(刊号 # 77 Oct 21, 2009)
    Java 依赖注射规范(JSR330)正式发布
    NetBeans IDE 6.8 里程碑 2 已经可用!
    Java 依赖注射规范(JSR330)正式发布
    对面向对象和面向过程的一些新理解
    NetBeans 时事通讯(刊号 # 76 Oct 13, 2009)
    Java EE 6 最终草案暗示了平台的未来发展方向
    “当前不会命中断点。源代码与原始版本不同”的问题的有效解决办法
  • 原文地址:https://www.cnblogs.com/nieaojie625/p/13669873.html
Copyright © 2011-2022 走看看