10-Java的IO流

1、File类

1.1、概述

  1. File: 翻译是文件,用于表达java中的路径名。
  2. java.io.File类: **文件和文件目录路径**的抽象表示形式,与平台无关
  3. File能新建、删除、重命名文件和目录,但File不能访问文件内容本身。如果需要访问文件内容本身,则需要使用输入、输出流。
  4. 想要在Java程序中表示一个真实存在的文件或目录,那么必须有一个File对象,但是Java程序中的一个File对象,可能没有一个真实存在的文件或目录
  5. File对象可以作为参数传递给流的构造器。

1.2、File类的使用

1.2.1、File类的理解

  1. File类的一个对象,代表一个文件或一个文件目录(俗称: 文件夹)
  2. File类声明在java.io包下。
  3. File类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法,并未涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容,必须使用IO流来完成。
  4. 想要在Java程序中表示一个真实存在的文件或目录,那么必须有一个File对象,但是Java程序中的一个File对象,可能没有一个真实存在的文件或目录。
  5. 后续File类的对象常会作为参数传递到流的构造器中,指明读取或写入的"终点"。

1.2.2、常用构造器

在这里插入图片描述

1.2.3、路径分隔符

  • 路径中的每级目录之间用一个 路径分隔符 隔开。
  • 路径分隔符和系统有关:
    • windows和Dos系统默认使用 " \ "来表示
    • UNIX和URL使用" / "来表示
  • Java程序支持跨平台运行,因此路径分隔符要慎用。
  • 为了解决这个隐患,File类提供了一个常量: **public static final String separator**根据操作系统,动态的提供分隔符
  • 图示:
    • 在这里插入图片描述

1.2.4、如何创建File类的实例化

//实例化
File file = new File(String filePath);
File file2 = new File(String parentPath,String childPath);
File file3 = new File(File parent,String child);

相对路径: 相较于某个路径下,指明的路径

绝对路径: 包含盘符在内的文件或文件目录的路径

//构造器1
File file1 = new File("hello.txt");
File file2 = new File("E:\\workspace_idea\\JavaSenic\\IO\\hello.txt");
//构造器2
File file2 = new File("E:\\workspace_idea","JavaSenic");
//构造器3
File file3 = new File(file2,"hello.txt");

1.2.5、File类的常用方法

File类的获取功能

  • public String getAbsolutePath():获取绝对路径
  • public String getPath():获取路径
  • public String getName() :获取名称
  • public String getParent():获取上层文件目录路径。若无,返回null
  • public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
  • public long lastModified() :获取最后一次的修改时间,毫秒值
  • 如下的两个方法适用于文件目录:
  • public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
  • public File[] listFiles():获取指定目录下的所有文件或者文件目录的File数组,以绝对路径方式展示。

//代码示例
@Test
    public void test2(){
        File file1 = new File("hello.txt");
        File file2 = new File("d:\\io\\hi.txt");
        //public String getAbsolutePath()`:获取绝对路径
        System.out.println(file2.getAbsolutePath());//d:\io\hi.txt
        //`public String getPath() `:获取路径
        System.out.println(file1.getPath());//hello.txt
        //`public String getName()` :获取名称
        System.out.println(file1.getName());//hello.txt
        //`public String getParent()`:获取上层文件目录路径。若无,返回null
        System.out.println(file2.getParent());//d:\io
        //`public long length()` :获取文件长度(即:字节数)。不能获取目录的长度。
        System.out.println(file1.length());
        //`public long lastModified()` :获取最后一次的修改时间,毫秒值
        System.out.println(file1.lastModified());

        File file = new File("D:\\编程资料\\JAVA\\java尚蛙谷\\1_课件");
        //`public String[] list()` :获取指定目录下的所有文件或者文件目录的名称数组
        String[] list = file.list();
        for (String s : list) {
            System.out.println(s);
        }
        //`public File[] listFiles() `:获取指定目录下的所有文件或者文件目录的File数组
        File[] files = file.listFiles();
        for (File file3 : files) {
            System.out.println(file3);
        }
    }

File类的重命名功能

  • public boolean renameTo(File dest):把文件重命名为指定的文件路径
  • 注意:file1.renameTo(file2)为例:要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在。就是把file1传递到file2的路径里面,并且修改命名为file2.
 //`public boolean renameTo(File dest)`:把文件重命名为指定的文件路径
//hello.txt传递到file1路径下,并且改名为h1.txt
        File file = new File("hello.txt");
        File file1 = new File("D:\\编程资料\\JAVA\\java尚蛙谷\\1_课件\\h1.txt");
        file.renameTo(file1);

File类的判断功能

  • public boolean isDirectory():判断是否是文件目录
  • public boolean isFile():判断是否是文件
  • public boolean exists() :判断是否存在
  • public boolean canRead() :判断是否可读
  • public boolean canWrite():判断是否可写
  • public boolean isHidden() :判断是否隐藏
//代码示例
@Test
    public void test4(){

//        public boolean isDirectory():判断是否是文件目录
//        public boolean isFile() :判断是否是文件
//        public boolean exists() :判断是否存在
//        public boolean canRead() :判断是否可读
//        public boolean canWrite() :判断是否可写
//        public boolean isHidden() :判断是否隐藏
        File file = new File("hello.txt");
        File file2 = new File("D:\\编程资料\\JAVA\\java尚蛙谷\\1_课件");
        System.out.println(file2.isDirectory());
        System.out.println(file.isFile());
        System.out.println(file.exists());
        System.out.println(file.canRead());
        System.out.println(file.canWrite());
        System.out.println(file.isHidden());

    }

File类的创建功能

  • 创建硬盘中对应的文件或文件目录
  • public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false
  • public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。
  • public boolean mkdirs():创建文件目录。如果此文件目录存在,就不创建了。如果上层文件目录不存在,一并创建
@Test
    public void test5() throws IOException {

        File file = new File("D:\\编程资料\\JAVA\\java尚蛙谷\\1_课件\\a\\b");
        //路径里文件(文本)没有,会帮助它自动创建,有就不会在创建
        //file.createNewFile();
        //路径里文件夹没有,会帮助它自动创建,有就不会在创建
        //file.mkdir();
        //路径里文件夹及上层目录没有,会帮助它自动创建,有就不会在创建
        file.mkdirs();
    }

File类的删除功能

  • 删除磁盘中的文件或文件目录
  • public boolean delete():删除文件或者文件夹
  • 删除注意事项:Java中的删除不走回收站。
 @Test
    public void test6(){
        File file = new File("hello.txt");
        if (file.exists()){
            file.delete();
            System.out.println("删除成功");
        }
    }

2、IO流

2.1、原理

  • I/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等。
  • Java程序中,对于数据的输入/输出操作以"流(stream)"的方式进行。
  • java.io包下提供了各种"流"类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据。

2.2、流的分类

操作数据单位:字节流、字符流

  • 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
  • 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用字节流处理

数据的流向:输入流、输出流

  • 输入input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中。
  • 输出output:将程序(内存)数据输出到磁盘、光盘等存储设备中。

流的角色:节点流、处理流

节点流:直接从数据源或目的地读写数据。

在这里插入图片描述

处理流:不直接连接到数据源或目的地,而是“连接”在已存在的流(节点流或处理流)之上,通过对数据的处理为程序提供更为强大的读写功能。

在这里插入图片描述

图示:

在这里插入图片描述

2.3、IO流的体系分类

2.3.1、总体分类

在这里插入图片描述

红框为抽象基类,蓝框为常用IO流

2.3.2、常用的几个IO流结构

抽象基类节点流(或文件流)缓冲流(处理流的一种)
InputStreamFileInputStream (read(byte[] buffer))BufferedInputStream (read(byte[] buffer))
OutputStreamFileOutputStream (write(byte[] buffer,0,len)BufferedOutputStream (write(byte[] buffer,0,len) / flush()
ReaderFileReader (read(char[] cbuf))BufferedReader (read(char[] cbuf) / readLine())
WriterFileWriter (write(char[] cbuf,0,len)BufferedWriter (write(char[] cbuf,0,len) / flush()

3、节点流

3.1、文件字符流FileReader的使用

1.1文件的输入

从文件中读取到内存(程序)中

步骤:

  1. 建立一个流对象,将已存在的一个文件加载进流 FileReader fileReader = new FileReader(new File(“Hello. txt”));
  2. 创建一个临时存放数据的数组 char[] ch = new char[1024];
  3. 调用流对象的读取方法将流中的数据读入到数组中。 fileReader.read(c1);
  4. 关闭资源。 fileReader.close();
@Test
    public void test()  {
        FileReader fileReader = null;
        try {
            File file = new File("hello.txt");
            fileReader = new FileReader(file);
            char[] c1 = new char[1024];
            int len;
            //判断,每次读五个字节赋给len,保证不等于-1往下执行
            while ((len = fileReader.read(c1)) != -1){
                //根据读到字符的长度放到string里面,从0开始。
                String s = new String(c1, 0, len);
                System.out.print(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileReader!=null){
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

图解:

在这里插入图片描述

注意点:

  1. read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1
  2. 异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理
  3. 读入的文件一定要存在,否则就会报FileNotFoundException。

3.2、文件字符流FileWriter的使用

1.2 文件的输出

从内存(程序)到硬盘文件中

步骤

  1. 创建流对象,建立数据存放文件 File Writer fw = new File Writer(new File(“Test.txt”))
  2. 调用流对象的写入方法,将数据写入流 fw.write(“我爱中国”)
  3. 关闭流资源,并将流中的数据清空到文件中。 fw.close();
//代码示例
@Test
    public void test(){
       FileWriter fileWriter = null;
       try {
           //1.提供File类的对象,指明写出到的文件
           File file = new File("Test.txt");
           //2.提供FileWriter的对象,用于数据的写出
           fileWriter = new FileWriter(file);
           //3.写出的操作
               fileWriter.write("我爱中国");
       }catch (Exception e){
           e.printStackTrace();
       }finally {
           try {
               //4.关闭流
               fileWriter.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
   }

注意点:

  1. 输出操作,对应的File可以不存在的,并不会报异常。
  2. File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
  3. File对应的硬盘中的文件如果存在:
    1. 如果流使用的构造器是:FileWriter(file,false)/FileWriter:对原有文件的覆盖。
    2. 如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件的基础上追加内容。

小练习

使用FileReader和FileWriter实现文件文本的复制

@Test
    public void test(){
       FileWriter fileWriter = null;
       FileReader fileReader = null;
       try {
           //1.创建File类的对象
           File file = new File("Test.txt");
           //2.创建输入流和输出流的对象
           fileWriter = new FileWriter(file);
           fileReader = new FileReader(new File("hello.txt"));
           //3.数据的读入和写出的操作
           char[] chars = new char[50];
           //记录每次读入到chars数组中的字符的个数
           int len;
           while ((len = fileReader.read(chars))!=-1){
               //每次写出len个字符
               fileWriter.write(chars,0,len);
           }
       }catch (Exception e){
           e.printStackTrace();
       }finally {
           try {
               //4.关闭流
               fileWriter.close();
               fileReader.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
   }

3.3、字节流FileInputSteam和FileOutputSteam的使用

文件字节流操作与字符流操作类似,只是实例化对象操作和数据类型不同。

//代码示例
 @Test
    public void test2(){
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            //1.创建File对象
            File file = new File("1.jpg");
            //2.创建操流
            fileInputStream = new FileInputStream(file);
            fileOutputStream = new FileOutputStream(new File("2.jpg"));
           //3.复制的过程
            byte[] chars = new byte[50];
            int len;
            while ((len = fileInputStream.read(chars))!=-1){
                fileOutputStream.write(chars,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                //4.关闭流
                fileInputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

注意点

  • 定义路径时,可以用“/”或“\”。
  • 输出操作,对应的File可以不存在的。并不会报异常。
  • File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此图片。
  • File对应的硬盘中的文件如果存在:在输出的过程中,会覆盖。
  • 读取文件时,必须保证文件存在,否则会报异常。
  • 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
  • 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用字节流处理

4、缓冲流(开发使用)

4.1、缓冲流作用

缓冲流也称为处理流,缓冲流目的是提高程序读取和写出的性能。缓冲流也分为字节缓冲流和字符缓冲流。

使用缓冲流的好处是能够更高效的读写信息,原理是先将数据缓冲起来,然后一起写入或者读取出来。

处理流与节点流的对比图示

在这里插入图片描述

4.2、缓冲流实现类

对应节点流的4个实现类

  • BufferedInputStream
  • BufferedOutputStream
  • BufferedReader
  • BufferedWriter

4.3、使用说明

  • 当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区。
  • 当使用 BufferedInputStream读取字节文件时,BufferedInputStream会一次性从文件中读取8192个(8Kb),存在缓冲区中,直到缓冲区装满了,才重新从文件中读取下一个8192个字节数组。
  • 向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满,BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法flush()可以强制将缓冲区的内容全部写入输出流。
  • 关闭流的顺序和打开流的顺序相反。只要关闭最外层流即可,关闭最外层流也会相应关闭内层节点流。
  • flush()方法的使用:手动将buffer中内容写入文件。
  • 如果是带缓冲区的流对象的close()方法,不但会关闭流,还会在关闭流之前刷新缓冲区,关闭后不能再写出。

4.4、缓冲流的使用

使用BufferInputStream和BufferOutputStream实现非文本文件的复制

  @Test
    public void test() throws IOException {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try{
            //1.造文件
            File file = new File("1.jpg");
            File file1 = new File("3.jpg");
            //2.造流
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(new FileOutputStream(file1));
            //3.复制的细节:读取、写入
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) != -1){
                bos.write(bytes,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (bis !=null){
                bis.close();
            }
            if (bos != null){
                bos.close();
            }
        }
    }

使用BufferedReader和BufferedWriter实现文本文件的复制

 @Test
    public void test2(){
        BufferedReader br = null;
        BufferedWriter bw = null;
        try{
            //1.造文件
            File file = new File("hello.txt");
            File file1 = new File("hello4.txt");
            //2.造流
            br = new BufferedReader(new FileReader(file));
            bw = new BufferedWriter(new FileWriter(file1));
            //3.复制
            //方式一
//            char[] chars = new char[1024];
//            int len;
//            while ((len = br.read(chars)) !=-1){
//                bw.write(chars,0,len);
//            }
            //方式二
            String data;
            //一次读一行数据
            while ((data = br.readLine())!=null){
                bw.write(data);
                bw.newLine();
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //4.关闭流
            if (br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bw !=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

5、转换流

5.1、简介

  • 转换流提供了在字节流和字符流之间的转换
  • JavaAPI提供了两个转换流:
    • InputStreamReader: 将InputStream转换为Reader
    • OutputStreamWriter: 将Writer转换为OutputStream
  • 字节流中的数据都是字符时,转换字符流操作更高效。
  • 很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。

5.2、InputStreamReader

InputStreamReader将一个字节的输入流转换为字符的输入流 解码:字节、字节数组 —>字符数组、字符串

构造器:

  • public InputStreamReader(InputStream in)
  • public InputStreamReader(Inputstream in,String charsetName)//可以指定编码集

5.3、OutputStreamWriter

OutputStreamWriter将一个字符的输出流转换为字节的输出流 编码:字符数组、字符串 —> 字节、字节数组

构造器:

  • public OutputStreamWriter(OutputStream out)
  • public OutputStreamWriter(Outputstream out,String charsetName)//可以指定编码集

转换图示:

在这里插入图片描述

//代码示例
@Test
    public void test(){
        InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        try{
            //造文件
            File file = new File("hello.txt");
//            isr = new InputStreamReader(new FileInputStream(file));//使用系统默认的字符集
            //参数2指明了字符集,具体使用哪个字符集,取决于文件保存时使用的字符集
            isr = new InputStreamReader(new FileInputStream(file),"UTF-8");
            osw = new OutputStreamWriter(new FileOutputStream("hello5.txt"),"UTF-8");
            //读写过程
            char[] chars = new char[1024];
            int len;
            while ((len = isr.read(chars)) != -1){
                osw.write(chars,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (isr!=null){
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (osw!=null){
            try {
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

6、编码集

6.1、常见的编码表

  • ASCII:美国标准信息交换码。用一个字节的7位可以表示。
  • ISO8859-1:拉丁码表。欧洲码表用一个字节的8位表示。
  • GB2312:中国的中文编码表。最多两个字节编码所有字符
  • GBK:中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码
  • Unicode:国际标准码,融合了目前人类使用的所字符。为每个字符分配唯一的字符码。所有的文字都用两个字节来表示。
  • UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。

在这里插入图片描述

说明

  • 面向传输的众多UTF(UCS Transfer Format)标准出现了,顾名思义,UTF-8就是每次8个位传输数据,而UTF-16就是每次16个位。这是为传输而设计的编码,并使编码无国界,这样就可以显示全世界上所有文化的字符了。
  • Unicode只是定义了一个庞大的、全球通用的字符集,并为每个字符规定了唯确定的编号,具体存储成什么样的字节流,取决于字符编码方案。推荐的Unicode编码是UTF-8和UTF-16。

在这里插入图片描述

6.2、编码应用

  • 字符串–>字节数组
  • 解码:字节数组–>字符串
  • 转换流的编码应用
    • 可以将字符按指定编码格式存储
    • 可以对文本数据按指定编码格式来解读
    • 指定编码表的动作由构造器完成

使用要求

客户端/浏览器端 <----> 后台(java,GO,Python,Node.js,php) <----> 数据库

要求前前后后使用的字符集都要统一:UTF-8.

7、标准输入、输出流(了解)

7.1、简介

System.in:标准的输入流,默认从键盘输入

System.out:标准的输出流,默认从控制台输出

7.2、方法

System类的setIn(InputStream is) 方式重新指定输入的流

System类的setOut(PrintStream ps)方式重新指定输出的流。

7.3、使用示例

从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,

直至当输入“e”或者“exit”时,退出程序。

设计思路

方法一:使用Scanner实现,调用next()返回一个字符串

方法二:使用System.in实现。System.in —> 转换流 —> BufferedReader的readLine();

public class Test{
    public static void main(String[] args) throws IOException {
        InputStreamReader inputStreamReader = new InputStreamReader(System.in);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        while (true){
            System.out.println("请输入字符串");
            String data = bufferedReader.readLine();
            if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)){
                System.out.println("程序结束");
                break;
            }
            String upperCase = data.toUpperCase();
            System.out.println(upperCase);
        }
        bufferedReader.close();
    }
}

8、打印流(了解)

8.1、简介

1.实现将基本数据类型的数据格式转化为字符串输出
2.打印流:PrintStream和PrintWriter
提供了一系列重载的print()和println()方法,用于多种数据类型的输出
PrintStream和PrintWriter的输出不会抛出IOException异常
PrintStream和PrintWriter有自动flush功能
PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。
在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。
System.out返回的是PrintStream的实例

@Test
public void test2() {
    PrintStream ps = null;
    try {
        FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
        // 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
        ps = new PrintStream(fos, true);
        if (ps != null) {// 把标准输出流(控制台输出)改成文件
            System.setOut(ps);
        }


        for (int i = 0; i <= 255; i++) { // 输出ASCII字符
            System.out.print((char) i);
            if (i % 50 == 0) { // 每50个数据一行
                System.out.println(); // 换行
            }
        }


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

}

9、数据流(了解)

实现类

DataInputStream 和 DataOutputStream
分别“套接”在 InputStream 和 OutputStream 子类的流上

作用

用于读取或写出基本数据类型的变量或字符串

示例代码

将内存中的字符串、基本数据类型的变量写出到文件中。

@Test
public void test3(){
    //1.造对象、造流
    DataOutputStream dos = null;
    try {
        dos = new DataOutputStream(new FileOutputStream("data.txt"));
        //数据输出
        dos.writeUTF("Bruce");
        dos.flush();//刷新操作,将内存的数据写入到文件
        dos.writeInt(23);
        dos.flush();
        dos.writeBoolean(true);
        dos.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //3.关闭流
        if (dos != null){
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。

@Test
public void test4(){
    DataInputStream dis = null;
    try {
        //1.造对象、造流
        dis = new DataInputStream(new FileInputStream("data.txt"));
        //2.从文件读入数据
        String name = dis.readUTF();
        int age = dis.readInt();
        boolean isMale = dis.readBoolean();

        System.out.println("name:"+name);
        System.out.println("age:"+age);
        System.out.println("isMale:"+isMale);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //3.关闭流
        if (dis != null){

            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

10、对象流

10.1、实现类

ObjectInputStream

ObjectOutputStream

10.2、作用

用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。

10.3、序列化

序列化过程: 将内存中的java对象保存到磁盘中或通过网络传输出去

使用ObjectOutputStream实现

@Test
    public void test(){
        ObjectOutputStream ois = null;
        try{
            //创建对象,创建流
            ois = new  ObjectOutputStream(new FileOutputStream("Object.data"));
            ois.writeObject(new String("我爱北京天安门"));
            ois.flush();//刷新
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭流
            if (ois !=null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

10.4、反序列化

反序列化: 将磁盘文件中的对象还原为内存中的一个java对象

使用ObjectInputStream来实现

 @Test
    public void test2(){
        ObjectInputStream ois = null;
        try{
            ois = new ObjectInputStream(new FileInputStream("Object.data"));
            Object object = ois.readObject();
            String str = (String) object;
            System.out.println(str);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (ois != null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

10.5、自定义类

通过自定义类来实现序列化和反序列化

要想一个java对象是可序列化的,需要满足相应的要求。

  1. 需要实现接口: Serializable
  2. 当前类提供一个全局常量: public static final long serialVersionUID;
  3. 除了当前Person类需要实现Serializable接口之外,还必须保证其内部所属性也必须是可序列化的。(默认情况下,基本数据类型可序列化)

补充:ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量

//代码示例
//自定义类实现Serializable
public class Persion implements Serializable {
    public static final long serialVersionUID = 105456456l;
    private String name;
    int age;
	//无参构造器
    //有参构造器
    //set和get方法
    //toString()
}
//序列化
 @Test
    public void test3(){
        Persion persion = new Persion();
        persion.setName("张三");
        persion.setAge(20);
        ObjectOutputStream oos = null;
        try{
            oos = new ObjectOutputStream(new FileOutputStream("Object2.data"));
            oos.writeObject(persion);
            oos.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (oos!=null){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

//反序列化
 @Test
    public void test2(){
        ObjectInputStream ois = null;
        try{
            ois = new ObjectInputStream(new FileInputStream("Object2.data"));
            Object object = ois.readObject();
            Persion persion = (Persion) object;
            System.out.println(persion);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (ois != null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

11、随机存取文件流

11.1、实现类

RandomAccessFile

随机流(RandomAccessFile)不属于IO流,支持对文件的读取和写入随机访问。

11.2、简介

  • RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
  • RandomAccessFile既可以作为一个输入流,又可以作为一个输出流
  • RandomAccessFile类支持“随机访问”的方式,程序可以直接跳到文件的任意地方来读、写文件
    • 支持只访问文件的部分内容
    • 可以向已存在的文件后追加内容
  • RandomAccessFile对象包含一个记录指针,用以标示当前读写处的位置
  • RandomaccessFile类对象可以自由移动记录指针:
    • long getFilePointer():获取文件记录指针的当前位置
    • void seek(long pos):将文件记录指针定位到pos位置

11.3、如何使用

  1. 如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建。
  2. 如果写出到的文件存在,则会对原文件内容进行覆盖。(默认情况下,从头覆盖)
  3. 可以通过相关的操作,实现RandomAccessFile“插入”数据的效果。借助seek(int pos)方法
  4. 创建RandomAccessFile类实例需要指定一个mode参数,该参数指定RandomAccessFile的访问模式:
    • r:以只读方式打开
    • rw:打开以便读取和写入
    • rwd:打开以便读取和写入;同步文件内容的更新
    • rws:打开以便读取和写入;同步文件内容和元数据的更新
  5. 如果模式为只读r,则不会创建文件,而是会去读取一个已经存在的文件,读取的文件不存在则会出现异常。如果模式为rw读写,文件不存在则会去创建文件,存在则不会创建。
    @Test
    public void test4(){
        RandomAccessFile raf = null;
        RandomAccessFile raf2 = null;
        try{
            raf = new RandomAccessFile(new File("1.jpg"),"r");
            raf2 = new RandomAccessFile(new File("5.jpg"),"rw");
            byte[] bytes = new byte[1024];
            int len;
            while ((len = raf.read(bytes)) != -1){
                raf2.write(bytes,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭流
            if (raf !=null){
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (raf2 != null){
                try {
                    raf2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

12、流的基本应用总结

  • 流是用来处理数据的。

  • 处理数据时,一定要先明确数据源,与数据目的地数据源可以是文件,可以是键盘数据目的地可以是文件、显示器或者其他设备

  • 而流只是在帮助数据进行传输,并对传输的数据进行处理,比如过滤处理、转换处理等

  • 除去RandomAccessFile类外所有的流都继承于四个基本数据流抽象类InputSteam、OutputSteam、Reader、Writer

  • 不同的操作流对应的后缀均为四个抽象基类中的某一个[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传在这里插入图片描述

  • 不同处理流的使用方式都是标准操作:

    • 创建文件对象,创建相应的流
    • 处理流数据
    • 关闭流
    • 用try-catch-finally处理异常
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值