2021-10-20 I/O流详解

I/O流详解

1 I/O流概述

什么是I/O

输入输出,通过IO完成对硬盘文件的读和写。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fOLavPEN-1634718042075)(https://i.loli.net/2021/10/08/a5hEyirkJK2toqc.png)]

I/O流分类

**方式一:**按照流的方向:读和写=输入和输出

**方式二:**按照读取数据的方式不同:

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

    假设文件file1.txt,采用字节流的话是这样读的:
    a中国bc张三fe
    第一次读:一个字节,正好读到’a’(win下a占一个字节,Java下a占两个字节)
    第二次读:一个字节,正好读到‘中’字符的一半。
    第三次读:一个字节,正好读到‘中’字符的另外一半。

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

    假设文件file1.txt,采用字符流的话是这样读的:
    a中国bc张三fe
    第一次读:'a’字符(a’字符在windows系统中占用1个字节。)
    第二次读:‘中’字符(中字符在windows系统中占用2个字节。)

*Java中所有流都在java.io.

java I/O流四大家族:

四大家族首领:
java.io.Inputstream 字节输入流
java.io.Outputstream 字节输出流
java . io . Reader 字符输入流
java . io . Writer 字符输出流
以上都是抽象类

所有流都是可关闭的,都实现了java.io.Closeable接口。所有的输出流都实现了java.io.Flushable接口,都是可刷新的。

养成好习惯:

  1. 用完流之后一定要关闭,close();
  2. 用完输出流之后一定要flush();刷新一下。这个刷新表示将通道/管道当中剩余未输出的数据强行输出完(清空管道!)刷新的作用就是清空管道。

注意:以stream结尾的都是字节流,以reader/writer结尾是字符流

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

2 java.io.FileInputStream

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

Test01

读取基本操作

package com.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileInputStreamTest01 {
    public static void main(String[] args) {
        //创建文件字节输入流对象
        //D:\OneDrive - guyuer\JavaSE\File
        FileInputStream fis = null;
        try {
            //FileInputStream fis = new FileInputStream("D:\\OneDrive - guyuer\\JavaSE\\File\\temp01.txt");
            //写成这个也可以
            fis = new FileInputStream("D:/OneDrive - guyuer/JavaSE/File/temp01.txt");   //abc def

            //开始读
            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);   //32
            readData = fis.read();
            System.out.println(readData);   //100
            readData = fis.read();
            System.out.println(readData);
            readData = fis.read();
            System.out.println(readData);   //102
            readData = fis.read();
            System.out.println(readData);   //-1


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //在finally语句块中确保流一定关闭。
            if(fis != null){
                //关闭流的前提是流不为空,空流不用关
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Test02

改进的循环读取法

package com.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

//循环读取
public class FileInputStreamTest02 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("D:\\OneDrive - guyuer\\JavaSE\\File\\temp01.txt");   //abcdef

            /*while (true){
                int readData = fis.read();
                if(readData == -1){
                    break;
                }
                System.out.println(readData);
            }
*/
            System.out.println("==============");
            //改造循环方法
            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();
                }
            }
        }


    }
}

Test03

int read ( byte[] b)

一次最多读取b.length个字节。
减少硬盘和内存的交互,提高程序的执行效率。

相对路径
//IDEA默认目录是project的根目录
fis = new FileInputStream("tempfile.txt");
fis = new FileInputStream("src/com/io/tempfile4");
package com.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileInputStreamTest03 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            //IDEA默认目录是project的根目录
//            fis = new FileInputStream("tempfile.txt");
            fis = new FileInputStream("src/com/io/tempfile4");
            byte[] bytes = new byte[4];
            int readCount = fis.read(bytes);    //返回的是读到的字节的数量
            System.out.println(readCount);      //4
            System.out.println(new String(bytes));  //用String的构造方法将bytes数组转换为String,abcd
            //不应该全部转换,应该取多少字节转换多少
            System.out.println(new String(bytes,0,readCount));  //abcd

            readCount = fis.read(bytes);
            System.out.println(readCount);      //2
            System.out.println(new String(bytes));  //efcd
            System.out.println(new String(bytes,0,readCount));  //ef

            readCount = fis.read(bytes);
            System.out.println(readCount);      //-1,没读到


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

FileInputStream终极版

package com.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("src/tempfile2");
            byte[] bytes = new byte[100];   //中文乱码可以将数组改大
            /*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();
                }
            }
        }

    }
}

FileInputStream的其他方法

int available():返回流当中剩余的没有读到的字节数量
long skip(long n):跳过几个字节不读。

package com.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileInputStreamTest05 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        //available,返回流当中剩余的没有读到的字节数量
        try {
            fis = new FileInputStream("tempfile.txt");
            /*System.out.println("总字节数"+fis.available());
            //int readData = fis.read();
            //System.out.println("还剩"+fis.available()+"个字节没有读");

            //直接创建一个文件长度的数组,但是不太适合大文件,因为数组太大不行
            byte[] bytes = new byte[fis.available()];
            int readCount = fis.read(bytes);
            System.out.println(new String(bytes));      //abcdefg*/

            //skip跳过几个读取方法
            fis.skip(3);
            System.out.println(fis.read());     //100--d


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

3 java.io.FileOutputStream

package com.io;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class FileOutputStreamTest01 {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            //fos = new FileOutputStream("outfile");  //文件不存在会自动新建,存在会覆盖
            fos = new FileOutputStream("outfile",true);  //true表示在源文件末尾续写

            byte[] bytes = {97,98,99,100,101};  //会转换成字符
            //全部写出
            fos.write(bytes);
            fos.write(32);
            //部分写出
            fos.write(bytes,0,3);

            String s = "\nhexo.guyuer.xyz";
            byte[] bytes1 = s.getBytes(StandardCharsets.UTF_8);
            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();
                }
            }
        }
    }
}

4 文件复制

文件复制原理

使用FileInputStream和FileOutputStream。

package com.io;

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

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

        try {
            fis = new FileInputStream("D:\\OneDrive - guyuer\\Java\\File\\飞天狗.png");
            fos = new FileOutputStream("D:\\OneDrive - guyuer\\Java\\File\\c.png");

            byte[] bytes = new byte[1024 * 1024]; //1024字节B是1k,这是1024k,是1M
            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,不要一起try,要不然一个报异常,另一个的就不能关闭了
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            }
        }

    }
}

使用FileReader和FileWriter。

package com.io;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

//使用reader和writer只能拷贝文本文件
public class CopyTest02 {
    public static void main(String[] args) {
        FileReader in = null;
        FileWriter out = null;
        try {
            in = new FileReader("tempfile.txt");
            out = new FileWriter("copyfile.txt");

            char[] chars = new char[1024*512];
            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();
                }
            }
        }
    }
}

5 java.io.FileReader和java.io.FileWriter

FileReader

文件字符输入流,只能读取普通文本。

读取文本内容时,比较方便,快捷。

package com.io;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderTest01 {
    public static void main(String[] args) {
        FileReader reader = null;
        try {
            reader = new FileReader("tempfile.txt");
            char[] chars = new char[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

文件字符输出流。

只能输出普通文本。

package com.io;

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterTest01 {
    public static void main(String[] args) {
        FileWriter writer = null;
        try {
            writer = new FileWriter("writefile");
            char[] chars = {'我','的','博','客'};
            String s = "hexo.guyeur.xyz";
            writer.write(chars);
            writer.write("\n");
            writer.write(s);        //可以直接写字符串
            writer.write("\n");
            writer.write("我是一名Java软件工程师");

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

    }
}

6 java.io.BufferedReader和java.io.BufferedWriter

带有缓冲区的字符输入流和输出流

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

BufferedReader

package com.io;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class BuffferedReadertTest01 {
    public static void main(String[] args) throws IOException {
        FileReader reader = new FileReader("src/com/io/FileInputStreamTest01.java");
        BufferedReader br = new BufferedReader(reader);
        //当一个流的构造方法中需要一个流的时候,这个被传进来的流叫做:节点流。
        //外部负责包装的这个流,叫做:包装流,还有一个名字叫做:处理流。
        //像当前这个程序来说:FileReader就是一个节点流。BufferedReader就是包装流/处理流。

        //读一行,不带换行符
        /*String firstLine = br.readLine();
        System.out.println(firstLine);*/

        String s = null;
        while ((s= br.readLine())!=null){
            System.out.println(s);
        }
        //关闭流
        //对于包装流来说,只需要关闭最外层流就行,里面的节点流会自动关闭。(可以看源代码。)
        br.close();
    }
}

转换流

package com.io;

import java.io.*;

public class BuffferedReadertTest02 {
    public static void main(String[] args) throws IOException {
        //字节流
        FileInputStream in = new FileInputStream("src/com/io/FileInputStreamTest01.java");
        //通过转换流转换,将InputStream转换为Reader
        //这里in是节点流。reader是包装流。
        InputStreamReader reader = new InputStreamReader(in);
        //这个构造方法只能传一个字符流。不能传字节流。
        //reader是节点流。br是包装流。
        BufferedReader br = new BufferedReader(reader);
        BufferedReader br1 = new BufferedReader(new InputStreamReader(new FileInputStream("src/com/io/FileInputStreamTest01.java")));
        String s = null;
        while ((s=br.readLine())!=null){
            System.out.println(s);
        }
        System.out.println("============================================");
        while ((s = br1.readLine()) != null){
            System.out.println(s);
        }

        br.close();
        br1.close();
    }
}

BufferedWriter

package com.io;

import java.io.*;

public class BuffferedWriterTest {
    public static void main(String[] args) throws IOException {
        //BufferedWriter out = new BufferedWriter(new FileWriter("bw"));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("bw")));
        out.write("hello World!\n");
        out.write("你好");
        out.write("套娃");
        out.flush();
        out.close();
    }
}

7 java.io.DataOutputStream和 java.io.DataInputStream

DataOutputStream

数据专属的流

这个流可以将数据连同数据的类型一并写入文件。

注意:这个文件不是普通文本文档。(这个文件使用记事本打不开)

package com.io;

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

public class DataOutputStreamTest {
    public static void main(String[] args) throws IOException {
        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();
    }
}

DataInputStream

DataInputStream:数据字节输入流。

DataOutputstream写的文件,只能使用DataInputstream去读。并且读的时候你需要提前知道写入的顺序。

读的顺序需要和写的顺序一致。才可以正常取出数据。

package com.io;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class DataInputStreamTest {
    public static void main(String[] args) throws IOException {
        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);
        System.out.println(l);
        System.out.println(f);
        System.out.println(d);
        System.out.println(sex);
        System.out.println(c);
               

        dis.close();
    }
}

8 标准输出流PrintStream&WriteStream

java.io.Printstream

标准的字节输出流。默认输出到控制台。标准输出流不需要手动关闭。

package com.io;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class PrintStreamTest {
    public static void main(String[] args) throws FileNotFoundException {
        //合并在一起
        System.out.println("hello");
        PrintStream out = System.out;
        //分开写
        out.println("张三");
        out.println("lisi");

        //改变输出方向
        //向log文件输出,不再指向控制台
        PrintStream ps = new PrintStream(new FileOutputStream("log"));
        //将输出方向修改为log
        System.setOut(ps);
        ps.println("guyue");
        ps.println("hhh");


    }
}

日志Log工具

package com.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){
        PrintStream out = null;
        try {
            out = new PrintStream(new FileOutputStream("log.txt",true));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        System.setOut(out);

        Date nowTime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String strTime = sdf.format(nowTime);

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

    }

}
/*
package com.io;

public class Test {
    public static void main(String[] args) {
        Logger.log("调用了方法1");
        Logger.log("调用了方法2");
        Logger.log("调用了方法3");
        Logger.log("调用了方法4");
    }
}
 */

9 Java.io.File类

概述

  1. 文件和目录都是File

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

  3. File对象代表什么?

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

  4. 需要掌握File类中常用的方法

常用方法

package com.io;

import java.io.File;
import java.io.IOException;

public class FileTest01 {
    public static void main(String[] args) throws IOException {
        //创建一个File对象
        File f1 = new File("D:\\OneDrive - guyuer\\Java\\File\\filetest");

        //判断是否存在!
        System.out.println(f1.exists());

        //如果不存在,则以文件的形式创建出来

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

        //如果不存在,则以目录的形式创建出来

        /*if(!f1.exists()){
        //以目录的形式新建。
        f1.mkdir();
        }*/


        //可以创建多重目录吗?
        File f2 = new File("D:\\OneDrive - guyuer\\Java\\File\\filetest\\1\\1");
        if(!f2.exists()){
            f2.mkdirs();
        }

        //获取文件父路径
        File f3 = new File("D:\\OneDrive - guyuer\\Java\\File\\temp01.txt");
        String parentpath = f3.getParent();
        System.out.println(parentpath);
        File parentFile = f3.getParentFile();
        System.out.println("获取绝对路径;"+parentFile.getAbsolutePath());

        File f4 = new File("copyfile");
        System.out.println(f4.getAbsolutePath());

    }
}
package com.io;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileTest02 {
    public static void main(String[] args) {
        //获取文件名
        File f = new File("D:\\OneDrive - guyuer\\Java\\File\\c.png");
        System.out.println("文件名:"+f.getName());
        //判断否是文件或目录
        System.out.println(f.isDirectory());
        System.out.println(f.isFile());
        //获取文件最后一次修改时间
        long t = f.lastModified();      //1970到现在总毫秒数
        Date time = new Date(t);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        String strTime = sdf.format(time);
        System.out.println(strTime);
        //获取文件大小
        System.out.println(f.length()); //101109字节B



    }
}
package com.io;

import java.io.File;

//ListFile()
//获取当前目录下所有子目录
public class FileTest03 {
    public static void main(String[] args) {
        File f = new File("D:\\OneDrive - guyuer\\Java\\File");
        File[] files = f.listFiles();
        for(File file : files){
            System.out.println(file.getAbsolutePath());
            System.out.println("================");
            System.out.println(file.getName());
        }
    }
}

作业

拷贝目录

将D:\course拷贝到c盘根下…

需要使用到:

FileInputstream

FileOutputstream

File

可能需要使用到递归。你尝试实现一下!

package com.io;

import sun.security.krb5.internal.crypto.Des;

import java.io.*;

public class CopyAll {
    public static void main(String[] args) {
        File srcFile = new File("D:\\OneDrive - guyuer\\Java\\File");
        File destFile = new File("D:\\OneDrive - guyuer\\test\\");

        copyDir(srcFile,destFile);

    }

    private static void copyDir(File srcFile, File destFile) {
        if(srcFile.isFile()){
            //一边读一边写

            FileInputStream in = null;
            FileOutputStream out = null;
            try {
                in = new FileInputStream(srcFile);
                //第一次读到的是文件,则会在不存在的文件夹下创建文件,bug.
                String path = destFile.getAbsolutePath()+srcFile.getAbsolutePath().substring(30);
                System.out.println(path);
                out = new FileOutputStream(path);
                byte[] bytes = new byte[1024*1024];
                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(in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(out != null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            return;
        }
        //获取源下面的子目录
        File[] files = srcFile.listFiles();
        for(File file : files){
            //这里有个bug,如果第一次读到的是文件,则会提示系统找不到指定目录。FileNotFoundException
            if(file.isDirectory()){
                //新建对应目录

                String strDir = file.getAbsolutePath();

                String destDir = destFile.getAbsolutePath()+strDir.substring(30);
                //System.out.println(destDir);

                File newFile = new File(destDir);
                if(!newFile.exists()){
                    newFile.mkdirs();
                }
            }
            //递归调用
            copyDir(file,destFile);
        }
    }
}

解决bug

package com.io;

//解决bug
import java.io.*;

public class CopyAll {
    public static void main(String[] args) {
        File srcFile = new File("D:\\OneDrive - guyuer\\Java\\File");
        File destFile = new File("D:\\OneDrive - guyuer\\test\\");
        if(!destFile.exists()){
            destFile.mkdirs();
        }

        copyDir(srcFile,destFile);

    }

    private static void copyDir(File srcFile, File destFile) {
        if(srcFile.isFile()){
            //一边读一边写
            FileInputStream in = null;
            FileOutputStream out = null;
            try {
                in = new FileInputStream(srcFile);

                String path = destFile.getAbsolutePath()+srcFile.getAbsolutePath().substring(30);
                System.out.println(path);
                out = new FileOutputStream(path);
                byte[] bytes = new byte[1024*1024];
                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(in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(out != null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            return;
        }
        //获取源下面的子目录
        File[] files = srcFile.listFiles();
        for(File file : files){
            if(file.isDirectory()){
                //新建对应目录

                String strDir = file.getAbsolutePath();

                String destDir = destFile.getAbsolutePath()+strDir.substring(30);
                //System.out.println(destDir);

                File newFile = new File(destDir);
                if(!newFile.exists()){
                    newFile.mkdirs();
                }
            }
            //递归调用
            copyDir(file,destFile);
        }
    }
}

10 序列化和反序列化

图解

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ABJq3Cns-1634718042083)(https://i.loli.net/2021/10/19/iBHsoP7JlN62D1t.png)]

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

注意:通过源代码发现,Serializable接口只是一个标志接口:
public interface Serializable {
}
这个接口当中什么代码都没有。
它的作用?
起到标识的作用,标志的作用,java虚拟机看到这个类实现了这个接口,可能会对这个类进行特殊待遇。

Serializable这个标志接口是给java虚拟机参考的,java虚拟机看到这个接口之后,会为该类自动生成
一个序列化版本号。

Java虚拟机看到Serializable接口之后,会自动生成一个序列化版本号。
这里没有手动写出来,java虚拟机会默认提供这个序列化版本号。

序列化

package com.bean;

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

public class ObjectOutputStreamTest01 {
    public static void main(String[] args) throws IOException {
        Student stu = new Student(111,"guyue");
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student"));

        oos.writeObject(stu);

        oos.flush();

        oos.close();

    }
}

/*
package com.bean;

import java.io.Serializable;

public class Student implements Serializable {
    int num;
    String name;

    public Student(int num, String name) {
        this.num = num;
        this.name = name;
    }

    public Student() {
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public String getName() {
        return name;
    }

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

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

 */

反序列化

package com.bean;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ObjectInputStreamTest01 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student"));
        Object stu = ois.readObject();
        System.out.println(stu);
        ois.close();
    }
}

一次序列化多个对象

将对象放到集合当中,序列化集合

package com.bean;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class ObjectOutputStreamTest02 {
    public static void main(String[] args) throws IOException {
        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();

    }
}
/*
package com.bean;

import java.io.Serializable;

public class User implements Serializable {
    int num;
    String name;

    public User(int num, String name) {
        this.num = num;
        this.name = name;
    }

    public User() {
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public String getName() {
        return name;
    }

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

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

 */

反序列化多个对象

package com.bean;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

public class ObjectInputStreamTest02 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("users"));
        List<User> userList = (List<User>)ois.readObject();
        for(User user : userList){
            System.out.println(user);
        }

        ois.close();

    }
}

transient关键字

transient关键字,表示游离,表示name属性不参与序列化操作

package com.bean;

import java.io.Serializable;

public class User implements Serializable {
    int num;
    //transient关键字,表示游离,表示name属性不参与序列化操作
    private transient String name;

    public User(int num, String name) {
        this.num = num;
        this.name = name;
    }

    public User() {
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public String getName() {
        return name;
    }

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

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

先序列化,后反序列化后输出内容如下:

User{num=1, name=‘null’}
User{num=2, name=‘null’}
User{num=3, name=‘null’}

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

版本号不一样会报异常

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

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

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

不同的人编写了同一个类,但“这两个类确实不是同一个类”。这个时候序列化版本就起上作用了。
对于java虚拟机来说,java虚拟机是可以区分开这两个类的,因为这两个类都实现了Serializable接口,都有默认的序列化版本号,他们的序列化版本号不一样。所以区分开了。

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

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

最终结论:

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

package com.bean;

import java.io.Serializable;

public class Student implements Serializable {
    //自定义序列化版本号
    private static final long serialVersionUID = 1234541244231321L;

    int num;
    String name;

    public Student(int num, String name) {
        this.num = num;
        this.name = name;
    }

    public Student() {
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public String getName() {
        return name;
    }

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

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

IDEA可以自动生产序列化版本号

11 IO+Properties的联合应用

Properties是一个Map集合,key和value都是string类型。

想将userinfo文件中的数据加载到Properties对象当中。

非常好的一个设计理念:

以后经常改变的数据,可以单独写到一个文件中,使用程序动态读取。将来只需要修改这个文件的内容,java代码不需要改动,不需要重新编译,服务器也不需要重启。就可以拿到动态的信息。

类似于以上机制的这种文件被称为配置文件。
并且当配置文件中的内容格式是:
key1=value
key2=value
的时候,我们把这种配置文件叫做属性配置文件。

java规范中有要求:属性配置文件建议以.properties结尾,但这不是必须的。
这种以.properties结居的文件在java中被称为:属性配置文件。
其中Properties是专门存放属性配置文件内容的一个类。

在属性配置文件中#号是注释

属性配置文件的key重复的话,value会自动覆盖!

package com.io;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class IoPropertiesTest01 {
    public static void main(String[] args) throws IOException {
        //新建一个输入流
        FileReader reader = new FileReader("src\\userinfo.properties");
        //新建Properties集合
        Properties pro = new Properties();
        pro.load(reader);

        String username = pro.getProperty("username");
        System.out.println(username);

        String password = pro.getProperty("password");
        System.out.println(password);

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值