首页 > 其他 > 详细

IO流

时间:2020-07-10 10:09:27      阅读:53      评论:0      收藏:0      [点我收藏+]

IO流

IO流概述

  • I : Input;O : Output
  • 通过IO可以完成硬盘文件的读和写。
  • Java中的IO流都已经写好了。java中所有的流都是在:java.io.*;下。
  • java中主要还是研究:怎么new流对象。调用流对象的哪个方法是读,哪个方法是写。
    技术分享图片

IO流分类

  • 有多种分类方式:
    • 一种方式是按照流的方向进行分类:以内存作为参照物,
      • 往内存中去,叫做输入(Input)。或者叫做读(Read)。
      • 从内存中出来,叫做输出(Output)。或者叫做写(Write)。
    • 另一种方式是按照读取数据方式不同进行分类:
      • 有的流是按照字节的方式读取数据,一次读取1个字节byte,等同于一次读取8个二进制位。这种流是万能的,什么类型的文件都可以读取。包括:文本文件,图片,声音文件,视频文件等....假设文件file1.txt,采用字节流的话是这样读的:a中国bc张三fe
        • 第一次读:一个字节,正好读到‘a‘
        • 第二次读:一个字节,正好读到‘中‘字符的一半。
        • 第三次读:一个字节,正好读到‘中‘字符的另外一半。
      • 有的流是按照字符的方式读取数据的,一次读取一个字符,这种流是为了方便读取普通文本文件而存在的,这种流不能读取:图片、声音、视频等文件。只能读取纯文本文件,连word文件都无法读取。假设文件file1.txt,采用字符流的话是这样读的:a中国bc张三fe
        • 第一次读:‘a‘字符(‘a‘字符在windows系统中占用1个字节。)
        • 第二次读:‘中‘字符(‘中‘字符在windows系统中占用2个字节。)
  • 综上所述:流的分类
    • 输入流、输出流
    • 字节流、字符流

IO流这块有四大家族

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

FileInputStream类的使用

  • 字节输入流,万能的,任何文件都可以采用这个流来读。
  • 字节的方式,完成输入的操作,完成读的操作(硬盘 --->内存)
public class FileInputStreamTest01 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
//          创建文件字节输入流对象
//          文件路径:F:\javaSETest\javaio\test(IDEA会自动把\变成\\,因为Java中\表示转义)
//            以下都是采用了绝对路径
//            FileInputStream fis = new FileInputStream("F:\javaSETest\javaio\test");
//            写成这个/也是可以的。
            fis = new FileInputStream("F:/javaSETest/javaio/test");
//            开始读
            int readData = fis.read();
            /*
            read()方法的返回值是:读取到的“字节”本身。
            如果读到文件末尾了,再度的时候读不到任何数据,返回-1
             */
            System.out.println(readData);//97
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//            在finally语句块之中确保流一定关闭
            if (fis != null) {//避免空指针异常
//                关闭流的前提是:流不为空,流是null的时候没必要关闭。
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
  • 使用循环,对上面的程序读取文件的方式进行优化改进
public class FileInputStreamTest02 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("F:/javaSETest/javaio/test");
            while (true) {
                int readData = fis.read();
                if (readData == -1) {
                    break;
                }
                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();
                }
            }
        }
    }
}
  • 改造上面程序的while循环,进而简化代码。
public class FileInputStreamTest02 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("F:/javaSETest/javaio/test");
//                改造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();
                }
            }
        }
    }
}
  • 分析上面程序的缺点:一次读取一个字节byte,这样内存和硬盘交互太频繁,基本上时间/资源都耗费在交互上面了。那么能不能一次读取多个字节呢?当然可以!
  • 对上面程序中的缺点进行改造,使用int read(byte[] b);一次最多读取b.length个字节。减少硬盘和内存的交互,提高程序的执行效率。往int[]数组当中读。
public class FileInputStreamTest03 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
//            相对路径一定是从当前所在的位置作为起点开始找!
//            IDEA默认的当前路径:工程project的根就是IDEA的默认路径。
            fis = new FileInputStream("F:/javaSETest/javaio/test");
//            开始读,采用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));
//            不应该全部转换,应该是读取了多少个字节,转换多少个
            System.out.println(new String(bytes, 0, readCount));

            readCount = fis.read(bytes);//第二次读到了3个字节
            System.out.println(readCount);//2
//            System.out.println(new String(bytes));//把byte[]数组转换成字符串的形式输出
            System.out.println(new String(bytes, 0, readCount));

            readCount = fis.read(bytes);//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();
                }
            }
        }
    }
}
  • 对上面程序进行改造
public class FileInputStreamTest04 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("F:/javaSETest/javaio/test");
//            准备一个byte数组
            byte[] bytes = new byte[4];
            while (true) {
                int readCount = fis.read(bytes);
                if (readCount == -1) {
                    break;
                }
//                把byte数组转换成字符串,读到多少个转换多少个
                System.out.println(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();
                }
            }
        }
    }
}
  • 继续改造,形成最终版,记住!
public class FileInputStreamTest04 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("F:/javaSETest/javaio/test");
//            准备一个byte数组
            byte[] bytes = new byte[4]; 
            int readCount = 0;
            while ((readCount = fis.read(bytes)) != -1) {
                System.out.println(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();返回流当中剩余的没有读到的字节数量。

public class FileInputStreamTest05 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("javaiotest");//这里使用的是相对路径
//            读一个字节
            int readByte = fis.read();
//            还剩下可以读的字节数量:6
            System.out.println("剩下多少个字节没有读:" + fis.available());//6
//
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
  • int available();这个方法的作用是什么?不需要使用循环了,直接的一次就够了。这种方式不适合太大的文件,因为byte[]数组不能太大。
public class FileInputStreamTest05 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("javaiotest");//这里使用的是相对路径
            System.out.println("总字节数量:" + fis.available());
/*//            读一个字节
            int readByte = fis.read();
//            还剩下可以读的字节数量:6
            System.out.println("剩下多少个字节没有读:" + fis.available());//6*/
            byte[] bytes = new byte[fis.available()];//这种方式不适合太大的文件,因为byte[]数组不能太大
//            不需要使用循环了
//            直接读一次就够了
            int readCount = fis.read(bytes);
            System.out.println(new String(bytes));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
  • long skip(long n);跳过几个字节不读。skip跳过几个字节不读取,这个方法也可能会用到!
public class FileInputStreamTest06 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("javaiotest");//这里使用的是相对路径
//            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;文件字节输出流,负责写。从内存写到硬盘。
  • 以下程序这种方式会将原文件清空重新写入,谨慎使用!
public class FileOutputStreamTest01 {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
//            这个“fileoutputstream”文件不存在的时候会自动新建
//            这种方式会将原文件清空重新写入,谨慎使用!
            fos = new FileOutputStream("F:\\javaSETest\\javaio\\fileoutputstream");
//          开始写
            byte[] bytes = {97, 98, 99, 100};
//            将byte数组全部写出!
            fos.write(bytes);//abcd
//            将byte数组的一部分写出
            fos.write(bytes, 0, 2);//
//            字符串
            String s = "我是一个中国人,我骄傲!";
            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();
                }
            }
        }
    }
}
  • 以追加的方式在文件末尾写入,不会清空原文件内容
public class FileOutputStreamTest02 {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
//              以追加的方式在文件末尾写入,不会清空原文件内容
            fos = new FileOutputStream("F:\\javaSETest\\javaio\\fileoutputstream", true);
//          开始写
            byte[] bytes = {97, 98, 99, 100};
//            将byte数组全部写出!
            fos.write(bytes);//abcd
//            将byte数组的一部分写出
            fos.write(bytes, 0, 2);
//            写完之后,最后一定要刷新!
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

文件复制原理(以字节流拷贝)

  • 使用FileInputStream和FileOutputStream完成文件的拷贝。拷贝的过程是一边读一边写。使用以上的字节流拷贝文件的时候,文件类型随意,万能的。什么样的文件都能拷贝。
    技术分享图片
public class CopyTest01 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
//            创建一个输入流对象
            fis = new FileInputStream("H:\\08-JavaSE进阶讲义\\JavaSE进阶-01-面向对象.pdf");
//            创建一个输出流对象
            fos = new FileOutputStream("F:\\javaSETest\\javaio\\JavaSE进阶-01-面向对象.pdf");
//            最核心的:一边读,一边写
            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的使用

  • 文件字符输入流,只能读取普通文本。读取文本内容时,比较方便,快捷。
public class FileReaderTest01 {
    public static void main(String[] args) {
        FileReader reader = null;
        try {
//            创建文件字符输入流
            reader = new FileReader("F:\\javaSETest\\javaio\\test");
//            开始读
            char[] chars = new char[4];//一次读取4个字符
            int readCount = 0;
            while ((readCount = reader.read(chars)) != -1) {
                System.out.println(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 FileWriterTest01 {
    public static void main(String[] args) {
        FileWriter out = null;
        try {
//            创建文件字符输出流
            out = new FileWriter("F:\\javaSETest\\javaio\\filewritertest");
//            开始写
            char[] chars = {‘我‘, ‘是‘, ‘中‘, ‘国‘, ‘人‘};
            out.write(chars);//写入的结果是:我是中国人
            out.write(chars, 2, 3);//
            /*
            写入的结果是:我是中国人中国人,
            这是在原有基础上添加“中国人”3个字,没有出现清空覆盖现象
             */
            out.write("我是一名Java软件工程师!");
//            刷新
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
  • 以追加的方式在文件末尾写入,不会清空原文件内容
public class FileWriterTest02 {
    public static void main(String[] args) {
        FileWriter out = null;
        try {
//            创建文件字符输出流
            out = new FileWriter("F:\\javaSETest\\javaio\\filewritertest", true);
//            开始写
            char[] chars = {‘我‘, ‘是‘, ‘中‘, ‘国‘, ‘人‘};
            out.write(chars);//写入的结果是:我是中国人
            out.write(chars, 2, 3);//
            /*
            写入的结果是:我是中国人中国人,
            这是在原有基础上添加“中国人”3个字,没有出现清空覆盖现象
             */
            out.write("我是一名Java软件工程师!");
//            写入一个换行符
            out.write("\n");
            out.write("helloworld!");
//            刷新
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

复制普通文本文件

  • 使用FileReader和FileWriter进行拷贝的话,只能拷贝普通文本文件。
public class CopyTest02 {
    public static void main(String[] args) {
        FileReader in = null;
        FileWriter out = null;
        try {
//            读
            in = new FileReader("H:\\08-JavaSE进阶讲义\\JavaSE进阶-02-数组.pdf");
//            写
            out = new FileWriter("F:\\javaSETest\\javaio\\JavaSE进阶-02-数组.pdf");
//            一边读一边写
            char[] chars = new char[1024 * 1024];//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数组。自带缓冲。
public class BufferedReaderTest01 {
    public static void main(String[] args) {
//        当一个流的构造方法需要一个流的时候,这个被传进来的流叫做:节点流。
//        外部负责包装的这个流叫做:包装流,还有一个名字叫做:处理流。
//        就当前这个程序来说,FileReader就是一个节点流;BufferedReader就是包装流/处理流
        FileReader reader = null;
        BufferedReader br = null;
        try {
            reader = new FileReader("F:\\javaSETest\\javaio\\test");
            br = new BufferedReader(reader);
            String s = null;
            //        br.readLine()方法读取一个文本行,但不带换行符
            while ((s = br.readLine()) != null) {
                System.out.println(s);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
//          关闭流
//        对于包装流来说,只需要关闭最外层的流就行,里面的节点流会自动关闭。
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
  • BufferedReader这个的构造方法只能传一个字符流,不能传字节流。如果使用字节流的话,需要先使用转换流把字节流装换成字符流才能使用BufferedReader
ublic class BufferedReaderTest02 {
    public static void main(String[] args) throws IOException {
//        字节流
        FileInputStream in = new FileInputStream("F:\\javaSETest\\javaio\\test");
//        通过转换流进行转换(InputStreamReader将字符流转换为字节流)
//        这里in是字节流;reader是包装流/处理流
        InputStreamReader reader = new InputStreamReader(in);
//        这个构造方法只能传一个字符流,不能传字节流
//        在这里,reader是节点流;br是包装流/处理流
        BufferedReader br = new BufferedReader(reader);
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

//        关闭最外层
        br.close();
    }
}
  • 对上面的程序进行简化
public class BufferedReaderTest03 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("F:\\javaSETest\\javaio\\test")));
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

//        关闭最外层
        br.close();
    }
}

BufferedWriter缓冲流的使用

  • BufferedWriter:带有缓冲的字符输出流。
public class BufferedWriterTest01 {
    public static void main(String[] args) throws IOException {
//        带有缓冲区的字符输出流
        BufferedWriter out = new BufferedWriter(new FileWriter("F:\\javaSETest\\javaio\\test"));
//        开始写
        out.write("helloworld");
        out.write("\n");
        out.write("hello kitty");
//        刷新
        out.flush();
//        关闭
        out.close();
    }
}
  • BufferedWriter这个的构造方法只能传一个字符流,不能传字节流。如果使用字节流的话,需要先使用转换流把字节流装换成字符流才能使用BufferedWriter
public class BufferedWriterTest02 {
    public static void main(String[] args) throws IOException {
//        带有缓冲区的字符输出流
//        BufferedWriter out = new BufferedWriter(new FileWriter("F:\\javaSETest\\javaio\\test"));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("F:\\javaSETest\\javaio\\test")));
//        开始写
        out.write("hello kitty");
        out.write("\n");
        out.write("helloworld");
//        刷新
        out.flush();
//        关闭
        out.close();
    }
}
  • 使用追加方式
public class BufferedWriterTest02 {
    public static void main(String[] args) throws IOException {
//        带有缓冲区的字符输出流
//        BufferedWriter out = new BufferedWriter(new FileWriter("F:\\javaSETest\\javaio\\test"));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("F:\\javaSETest\\javaio\\test", true)));
//        开始写
        out.write("hello kitty");
        out.write("\n");
        out.write("helloworld");
//        刷新
        out.flush();
//        关闭
        out.close();
    }
}

数据流

DataOutputStream数据字节输出流的使用

  • java.io.DataOutputStream:数据字节输出流。这个流可以将数据连同数据的类型一并写入文件。
  • 注意:这个文件不是普通文本文档(这个文件使用记事本打不开)
public class DataOutputStreamTest01 {
    public static void main(String[] args) throws IOException {
//        创建数据专属的字节输出流
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("F:\javaSETest\javaio\test"));
//        写数据
        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();
    }
}

DataInputStream数据字节输入流的使用

  • DataInputStream:数据字节输入流。
  • DataOutputStream写的文件,只能使用DataInputStream去读。并且在读的时候需要提前知道写入的顺序。读的顺序需要和写的顺序一致才可以正常取出数据。
public class DataInputStreamTest01 {
    public static void main(String[] args) throws IOException {
        DataInputStream dis = new DataInputStream(new FileInputStream("F:\\javaSETest\\javaio\\test"));
//        开始读
        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();
    }
}

标准输出流

  • java.io.PrintStream:标准的字节输出流。默认输出到控制台
public class PrintStreamTest01 {
    public static void main(String[] args) throws FileNotFoundException {
//        联合起来写
        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();
        System.exit(0);
        PrintStream PS2=System.out;
         System.arraycopy(...);
         */
//        标准输出流不再指向控制台,指向“F:\javaSETest\javaio\test”文件
        PrintStream printStream = new PrintStream(new FileOutputStream("F:\\javaSETest\\javaio\\test"));
//        修改输出方向,将输出方向修改到“F:\javaSETest\javaio\test”文件
        System.setOut(printStream);
//                再输出
        System.out.println("hello world");
        System.out.println("hello kitty");
        System.out.println("hello zhangsan");
    }
}
  • 使用标准输出流java.io.PrintStream编写一个日志工具
/*
日志工具
 */
public class Logger {
    /*
    记录日志的方法
     */
    public static void log(String msg) {
        try {
//            指向一个日志文件
            PrintStream out = new PrintStream(new FileOutputStream("F:\\javaSETest\\javaio\\test", 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();
        }
    }
}
public class LogTest {
    public static void main(String[] args) {
//        测试工具类是否好用
        Logger.log("调用了System的gc()方法,建议启动垃圾回收");
        Logger.log("调用了UserService的doSome()方法");
        Logger.log("用户尝试进行登录,验证失败!");
    }
}
/*
运行结果:
2020-07-09 20:53:29 624: 调用了System的gc()方法,建议启动垃圾回收
2020-07-09 20:53:29 772: 调用了UserService的doSome()方法
2020-07-09 20:53:29 773: 用户尝试进行登录,验证失败!
 */

File类

  • File类和四大家族没有关系,所以File类不能完成文件的读和写。
  • File对象代表什么?文件和目录路径名的抽象表达形式。F:\javaSETest\javaio这是一个File对象。一个File对象有可能对应的事目录,也可能事文件。 File只是一个路径名的抽象表达形式。
  • .File类中的常用方法(需要掌握)
public class FileTest01 {
    public static void main(String[] args) throws IOException {
//        创建一个File文件
        File f1 = new File("F:\\javaSETest\\javaio");
//        判断是否存在!
        System.out.println(f1.exists());
    }
}
public class FileTest01 {
    public static void main(String[] args) throws IOException {
//        创建一个File文件
        File f1 = new File("F:\\javaSETest\\javaio");
//        如果F:\javaSETest\javaio不存在,则以文件的形式创建出来
        if (!f1.exists()) {
//            以文件形式的新建
            f1.createNewFile();
        }
    }
}
public class FileTest01 {
    public static void main(String[] args) throws IOException {
//        创建一个File文件
        File f1 = new File("F:\\javaSETest\\javaio");
//        如果F:\javaSETest\javaio不存在,则以目录的形式创建出来
        if (!f1.exists()) {
//            以目录的形式新建
            f1.mkdir();
        }
    }
}
public class FileTest01 {
    public static void main(String[] args) throws IOException {
//        可以创建多重目录吗?可以
        File f2 = new File("F:\\javaSETest\\javaio\\a\\b\\c");
        if (!f2.exists()) {
//            多重目录的形式新建
            f2.mkdirs();
        }
    }
}
public class FileTest01 {
    public static void main(String[] args) throws IOException {
        File f3 = new File("F:\\javaSETest\\javaio");
//        获取文件的父路径
        String parentPath = f3.getParent();
        System.out.println(parentPath);//F:\javaSETest
        File parentFile = f3.getParentFile();
        System.out.println("获取绝对路径:" + parentFile.getAbsolutePath());//获取绝对路径:F:\javaSETest
    }
}
public class FileTest02 {
    public static void main(String[] args) {
//        创建File类对象
        File f1 = new File("F:\\javaSETest\\javaio");
//        获取文件名
        System.out.println("文件名:" + f1.getName());//文件名:javaio
    }
}
public class FileTest02 {
    public static void main(String[] args) {
//        创建File类对象
        File f1 = new File("F:\\javaSETest\\javaio");
//        判断是否是一个目录
        System.out.println(f1.isDirectory());//true
    }
}
public class FileTest02 {
    public static void main(String[] args) {
//        创建File类对象
        File f1 = new File("F:\\javaSETest\\javaio");
//        判断是否是一个文件
        System.out.println(f1.isFile());//false
    }
}
public class FileTest02 {
    public static void main(String[] args) {
//        创建File类对象
        File f1 = new File("F:\\javaSETest\\javaio");
//        获取文件最后一次修改时间
        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);//2020-07-09 21:30:20 266
    }
}
public class FileTest02 {
    public static void main(String[] args) {
//        创建File类对象
        File f1 = new File("F:\\javaSETest\\javaio");
//        获取文件大小
        System.out.println(f1.length());//4096字节
    }
}
  • File中的listFiles()方法
public class FileTest03 {
    public static void main(String[] args) {
//        File[] listFiles()
//        获取当前目录下所有子文件
        File f = new File("F:\\javaSETest\\javaio");
        File[] files = f.listFiles();
//        foreach
        for (File file : files) {
            System.out.println(file.getAbsolutePath());
        }
    }
}
/*
运行结果
F:\javaSETest\javaio\a
F:\javaSETest\javaio\fileoutputstream
F:\javaSETest\javaio\filewritertest
F:\javaSETest\javaio\JavaSE进阶-01-面向对象.pdf
F:\javaSETest\javaio\JavaSE进阶-02-数组.pdf
F:\javaSETest\javaio\test
 */

序列化与反序列化

序列化与反序列化的概述

  • 序列化(Serialize):java对象存储到文件中。将Java对象的状态保存下来的过程。
  • 反序列化(DeSerialize):将硬盘上的数据重新恢复到内存当中,恢复成Java对象。
    技术分享图片

序列化的实现

  • 参与序列化和反序列化的对象,必须实现Serializable接口。
  • 注意:通过源码发现,Serializable接口只是一个标志接口。
public interface Serializable {
}
  • 这个接口当中什么代码都有,那么它起到什么作用?
    • 起到标识的作用,标志的作用,Java虚拟机看到了这个类实现了这个接口,可能会对这个类有特殊待遇。
    • Serializable这个标志性接口是给Java虚拟机参考的,Java虚拟机看到这个接口之后,会为该类自动生成一个序列化版本号。
      序列号。
public class Student implements Serializable {
//    Java虚拟机看到Serializable接口之后,会自动生成一个序列化版本号。
//    这里没有手动写出来,Java虚拟机会默认提供这个序列化版本号。
    private int no;
    private String name;

    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;
    }

    @Override
    public String toString() {
        return "Student{" +
                "no=" + no +
                ", name=‘" + name + ‘\‘‘ +
                ‘}‘;
    }
}
public class ObjectOutputStringTest01 {
    public static void main(String[] args) throws IOException {
//        创建Java对象
        Student s = new Student(111, "zhangsan");
//        序列化
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("F:\\javaSETest\\javaio\\test"));
//        序列化对象
        oos.writeObject(s);
//        刷新
        oos.flush();
//        关闭
        oos.close();
    }
}

反序列化的实现

public class ObjectInputStreamTest01 {
    public static void main(String[] args) throws Exception {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("F:\\javaSETest\\javaio\\test"));
//        开始反序列化
        Object obj = ois.readObject();
//        反序列化回来是一个学生对象,所以会调用学生对象的etoString()方法
        System.out.println(obj);//Student{no=111, name=‘zhangsan‘}
        ois.close();
    }
}

序列化多个对象

序列化多个对象

  • 一次序列化多个对象,可以将对象放到集合中,序列化集合。
  • 注意:参与系列化的ArrayList集合以及集合中的元素User都需要实现java.io.Serializable接口
public class User implements Serializable {
    private int no;
    private String name;

    public User(int no) {
        this.no = no;
    }

    public User(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;
    }

    @Override
    public String toString() {
        return "User{" +
                "no=" + no +
                ", name=‘" + name + ‘\‘‘ +
                ‘}‘;
    }
}
public class ObjectOutputStringTest02 {
    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("F:\\javaSETest\\javaio\\test"));
//        序列化一个集合,这个集合中放了很多其他对象
        oos.writeObject(userList);
        oos.flush();
        oos.close();
    }
}

反序列化多个对象

/*
反序列化集合
 */
public class ObjectInputStreamTest02 {
    public static void main(String[] args) throws Exception {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("F:\\javaSETest\\javaio\\test"));
        List<User> userList = (List<User>) ois.readObject();
        for (User user : userList) {
            System.out.println(user);
        }
        ois.close();
    }
}
/*
运行结果:
User{no=1, name=‘zhangsan‘}
User{no=2, name=‘lisi‘}
User{no=3, name=‘wangwu‘}
 */

transient关键字

  • transient关键字表示游离的,不参与序列化。
public class User implements Serializable {
    private int no;
    private transient String name;//name 不参加序列化操作!
    ...
}

IO流

原文:https://www.cnblogs.com/yxc-160206/p/13277160.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!