IO流(复习)

IO流

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

File类提供的构造器

File(File parent, String child) 从父抽象路径名和子路径名字符串创建新的 File实例。
File(String pathname) 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例。
File(String parent, String child) 从父路径名字符串和子路径名字符串创建新的 File实例。

文件路径

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

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

  @Test
    public void test() {
        
        // 此过程只是new了一个实例,并没有对文件进行操作。有没有这个文件都不会报错
        // 第一种:File(String pathname)
        // 绝对路径
        File file = new File("C:\\java\\JAVA_NOTES\\1.JavaSE\\笔记\\fileTest.txt");
        // 相对路径:默认在 module 下
        File file1 = new File("fileTest.txt");
        System.out.println(file);

        // 第二种:File(String parent, String child)
        File file2 = new File("C:\\java\\JAVA_NOTES\\1.JavaSE", "笔记");
        System.out.println(file2);

        // 第三种:第二种:File(File parent, String child)
        File file3 = new File(file2, "fileTest.txt");
        System.out.println(file3);

    }

File 类中常用的方法

获取类方法

返回值描述
StringgetPath() 获取路径
StringgetAbsolutePath() 获取绝对路径
StringgetName() 获取文件名
StringgetParent() 返回文件上层目录名,若没有返回 null
longlastModified() 返回此抽象路径名表示的文件上次修改的时间。
longlength() 返回由此抽象路径名表示的文件的长度。
String[]list() 获取指定目录下的所有文件或者文件目录的名称数组
String[]list(FilenameFilter filter) 获取指定目录下的所有文件或者文件目录的File数组
文件重命名
booleanrenameTo(File dest) 把文件重命名为指定的文件路径 file1.renameTo(file2)为例: 要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在
    // File中常用的方法
    @Test
    public void test2() {
        // 绝对路径
        File file = new File("C:\\java\\JAVA_NOTES\\1.JavaSE\\笔记\\fileTest.txt");
        // 在单元测试中,相对路径:默认在 module 下,在 main 方法中,默认路径在此工程下
        File file2 = new File("fileTest.txt");
        System.out.println(file.getAbsolutePath());
        System.out.println(file.getPath());
        System.out.println(file.getName());
        System.out.println(file.getParent());
        System.out.println(file.length());
        System.out.println(new Date(file.lastModified()));

        System.out.println();

        System.out.println(file2.getAbsolutePath());
        System.out.println(file2.getPath());
        System.out.println(file2.getName());
        System.out.println(file2.getParent());
        System.out.println(file2.length());
        System.out.println(file2.lastModified());
        
    }

    @Test
    public void test3() {
        File file2 = new File("C:\\java\\JAVA_NOTES\\1.JavaSE", "笔记");
        File[] files = file2.listFiles();
        // 获取目录下的所有 file 文件
        for (File file: files) {
            System.out.println(file.getName());
        }
        // 获取目录下的所有 file 文件名
        String[] list = file2.list();
        for (String s:list) {
            System.out.println(s);
        }
    }

    @Test
    public void test4() {
        File file2 = new File("fileTest.txt");
        // file2 文件必须在硬盘上真实存在,修改的文件必须不存在
        boolean b = file2.renameTo(new File("fileTest2.txt"));
        System.out.println(b);
    }

判断类方法

返回值描述
booleanisDirectory() 测试此抽象路径名表示的文件是否为目录
booleanisFile() 测试此抽象路径名表示的文件是否为普通文件。
booleanisHidden() 测试此抽象路径名命名的文件是否为隐藏文件。
booleanexists() 测试此抽象路径名表示的文件或目录是否存在。
booleancanWrite() 判断是否可写
booleancanRead() 判断是否可读
    @Test
    public void test5() {
        File file1= new File("fileTest2.txt");
        System.out.println(file1.isDirectory());
        System.out.println(file1.isFile());
        System.out.println(file1.exists());
        System.out.println(file1.canRead());
        System.out.println(file1.canWrite());
        System.out.println(file1.isHidden());

    }

在硬盘上创建文件

返回值描述
booleancreateNewFile() 创建文件,若存在文件则不创建,不存在就创建
booleanmkdir() 创建由此抽象路径名命名的目录。
booleanmkdirs() 创建文件或目录,递归创建。
booleandelete() 删除文件
  @Test
    public  void test6() throws IOException {
        File file1= new File("C:\\java\\JAVA_NOTES\\1.JavaSE\\笔记\\fileTest2.txt");
        if (file1.createNewFile()) {
            System.out.println("创建fileTest2.txt成功。。。。");
        }
        if (new File("C:\\java\\JAVA_NOTES\\1.JavaSE\\笔记\\fileTest").mkdir()) {
            System.out.println("创建   fileTest目录   成功。。。。");
        }
        // file 目录不存在,使用mkdirs可递归创建
        if (new File("C:\\java\\JAVA_NOTES\\1.JavaSE\\笔记\\file\\fileTest3.txt").mkdirs()) {
            System.out.println("创建   file目录和fileTest3.txt文件   成功。。。。");
        }
        
        if(file1.exists()) {
            System.out.println("文件不存在");
        }else{
            // 删除
            file1.delete();
        }
    }

以上所有的操作并没有对文件进行修改,对文件的修改由 IO 流完成。一般 File 都用作参数供 IO 流使用。

IO流概述和分类

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

流的分类

  • 按操作数据单位不同分为:字节流(8 bit),字符流(16 bit)
  • 按数据流的流向不同分为:输入流,输出流
  • 按流的角色的不同分为:节点流,处理流
抽象基类字节流字符流
输入流InputStreamReader
输出流OutputStreamWriter
  1. Java的IO流共涉及40多个类,实际上非常规则,都是从如下4个抽象基类派生的。
  2. 由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。

img

IO流体系结构

img

节点流

FileReader

  • 从 硬盘上将文件读到内存中

使用说明:

  • file 文件一定是在硬盘上存在的,否则会报:FileNotException 异常
  • 使用 try-catch-finally 捕捉异常,并且在 finally 中关闭流(否则会内存泄漏)
  • read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1

使用默认的 read() 方法

public class FileReaderTest {
    public static void main(String[] args) {
         // 在主方法中,默认路径在项目工程下。
         File file = new File("file/fileTest.txt");
        System.out.println(file.getAbsoluteFile());
    }

    @Test
    public void test() {
        // 在单元测试中:默认路径在此模块下
        File file = new File("fileTest2.txt");
        FileReader fileReader = null ;
        try {
            fileReader = new FileReader(file);
            int data;
            // 读操作
            while((data = fileReader.read()) != -1) {
                System.out.print((char)data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                
                // 关闭流
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

使用 read(char cbuf[]) 重载方法

  // 使用 read重载方法
    @Test
    public void test2() {
        // 在单元测试中:默认路径在此模块下
        File file = new File("fileTest2.txt");
        FileReader fileReader = null ;
        try {
            fileReader = new FileReader(file);
            // 读操作
            char[] cubf = new char[10];
            int length ;
            //  read(char cbuf[]) : 返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1
            while((length = fileReader.read(cubf)) != -1) {
                // 错误写法一:因为最后一次读到cubf的个数不足10个,因此之前的字符没有被覆盖
                // for (int i = 0; i < cubf.length; i++) {
                //     System.out.print(cubf[i]);
                // }
                // 正确写法一:
                // for (int i = 0; i < length; i++) {
                //     System.out.print(cubf[i]);
                // }

                // 错误写法二:
                // System.out.print(new String(cubf,0,cubf.length));
                // 正确写法二: 
                System.out.print(new String(cubf,0,length));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                f (fileReader != null)
                // 关闭流
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

针对上面错误写法的解释:

最后一次读操作,不够 字符数组的长度,无法覆盖。

image-20221110170945976

FileWriter

  • 从内存中写出去到硬盘
  • 如果没有对应的文件,将会自动创建文件。
  • FileWriter fw = new FileWriter(file,true);
    • true: 表示在文件原有内容上追加内容
    • false或者不写: 表示覆盖原有文件
    @Test
    public void test() {
        File file = new File("fileTest3");
        FileWriter fw = null ;
        try {
            // 写操作
            // true: 表示在文件原有内容上追加内容
            // false或者不写: 表示覆盖原有文件
            fw = new FileWriter(file,true);
            fw.write("java\n");
            fw.write("c++");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
               if (fw != null)
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

文件复制案例

 @Test
    public void test() {
        File readFile = new File("fileTest3");
        File writeFile = new File("fileTest4");

        FileReader fr = null;
        FileWriter fw = null;
        try {
            fr = new FileReader(readFile);
            fw = new FileWriter(writeFile);

            char[] cubf = new char[10];
            int len;
            //读操作
            while ((len = fr.read(cubf)) != -1) {
                // 写操作
                fw.write(new String(cubf, 0, len));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

FileInputStream/FileOutputStream

  • 字符流无法处理图片、视频等二进制的字节数据,需要使用 字节输入/输出流
  • 使用字节流处理中文文本会出现乱码,因为字节流使用byte数组,而在 utf8 编码下,一个中文占三个字节。 一次可能存不下一个完整的中文。
  • 使用 FileInputStream/FileOutputStream 完成复制是没有问题的,不涉及显示的行为,不会出现乱码

结论

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

图片复制

  @Test
    public void test() {
        File file1 = new File("1.jpg");
        File file2 = new File("2.jpg");
        FileInputStream fis = null ;
        FileOutputStream fos = null ;
        try {
             fis = new FileInputStream(file1);
             fos = new FileOutputStream(file2);
             
             byte[] b = new byte[10];
             int len;
             while ((len = fis.read(b))!= -1) {
                 fos.write(b,0,len);
             }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

处理流

缓冲流

  • 缓冲流要“套接”在相应的节点流之上,根据数据操作单位可以把缓冲流分为:

    • BufferedInputStream和BufferedOutputStream
    • BufferedReader和BufferedWriter
  • 为了提高数据读写的速度,Java API提供了带缓冲功能的流类,在使用这些流类时,会创建一个内部缓冲区数组,缺省使用8192个字节(8Kb)的缓冲区。

  • flush()方法的使用:刷新缓冲区

  • 缓冲流的close()方法,不但会关闭流,还会在关闭流之前刷新缓冲区,关闭后不能再写出。

使用 BufferedInputStream 和 BufferedOutputStream 实现文件复制

 @Test
    public void test() {
        File file = new File("1.jpg");
        File file1 = new File("3.jpg");
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            FileOutputStream fos = new FileOutputStream(file1);

            // 缓冲字节流
             bis = new BufferedInputStream(fis);
             bos = new BufferedOutputStream(fos);

            byte[] b = new byte[1024];
            int len;
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 只需关闭处理流,节点流会自动关闭
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

使用 BufferedReader 和 BufferedWriter 实现文件复制

BufferedReader 中除了提供了 read 方法,还提供了一个 readLine 方法,表示:一次读取文件的一行数据。若不存在下一行,返回 null

  @Test
    public void test() {
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new FileReader(new File("fileTest4")));
            bw = new BufferedWriter(new FileWriter(new File("fileTest5")));
            char[] cbuf = new char[1024];
            // 第一种方法
            // int len ;
            // while( (len = br.read(cbuf)) != -1) {
            //     bw.write(cbuf,0,len);
            // }

            // 第二种方法
            //readLine: 一次读取文件的一行。
            String data;
            while ((data = br.readLine()) != null) {
                bw.write(data); // data中不包含换行符
                bw.newLine(); // 提供换行符
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bw!= null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

缓冲流节点流复制文件速度对比

封装成俩个方法:

节点流

  // 节点流实现文件复制的方法
    public static void fileCopyByNodeFlow(String src,String dest) {
        File file1 = new File(src);
        File file2 = new File(dest);
        FileInputStream fis = null ;
        FileOutputStream fos = null ;
        try {
            fis = new FileInputStream(file1);
            fos = new FileOutputStream(file2);

            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b))!= -1) {
                fos.write(b,0,len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

缓冲流

  public static void fileCopyByProcessStreams(String src,String dest) {
        File file = new File(src);
        File file1 = new File(dest);
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            FileOutputStream fos = new FileOutputStream(file1);

            // 缓冲字节流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            byte[] b = new byte[1024];
            int len;
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 只需关闭处理流,节点流会自动关闭
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

测试

    public static void main(String[] args) {
        // 测试节点流和缓冲流的速度
        long start = System.currentTimeMillis();
        // 节点流
        // FileCopyByNodeFlow.fileCopyByNodeFlow("C:\\Users\\杨照光\\Desktop\\1.mp4","C:\\Users\\杨照光\\Desktop\\2.mp4"); // 1006
        // 缓冲流
        FileCopyByProcessStreams.fileCopyByProcessStreams("C:\\Users\\杨照光\\Desktop\\1.mp4","C:\\Users\\杨照光\\Desktop\\3.mp4"); //389
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }

转换流

  • InputStreamReader : 实现将字节的输入流按指定字符集转换为字符的输入流。
    • public InputStreamReader(InputStreamin)
    • public InputSreamReader(InputStreamin,StringcharsetName)
  • OutputStreamWriter : 实现将字符的输出流按指定字符集转换为字节的输出流。
    • public OutputStreamWriter(OutputStreamout)
    • public OutputSreamWriter(OutputStreamout,StringcharsetName)

构造器中可指定 编码/解码 的字符集,不写就是系统默认的字符集。

写什么字符集取决于 文件 保存的时候指定的字符集。

  • 字节流中的数据都是字符时,转成字符流操作更高效。
  • 很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。

img

使用转换流操作带有中文的文本文件

使用字节流在读取中文时会出现乱码,使用转换流,用字节流读取,转换成字符流显示

  @Test
    public void test () {
        File file = new File("fileTest3");
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            // 第二个参数:编码格式,一般使用fileTest3文件保存时使用的编码
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            char[] cbuf = new char[10];
            int len;
            while((len = isr.read(cbuf)) != -1) {
                System.out.print(new String(cbuf,0,len));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

使用转换流完成文件复制,并且复制完要求文件为 gbk 编码

  @Test
    public void test1 () {
        InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        try {
            File file1 = new File("fileTest3");
            File file2 = new File("fileTest6");

            FileInputStream fis = new FileInputStream(file1);
            FileOutputStream fos = new FileOutputStream(file2);

            // 读进来的字符集
            isr = new InputStreamReader(fis,"utf-8");
            // 写出去的字符集
            osw = new OutputStreamWriter(fos,"gbk");

            char[] cbuf = new char[1024];
            int len;
            while((len = isr.read(cbuf)) != -1) {
                osw.write(cbuf,0,len);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

其他流

标准的输入/输出流

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

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

  • System.in的类型是InputStream

  • System.out的类型是PrintStream,FilterOutputStream的子类

  • 重定向:通过System类的setIn,setOut方法对默认设备进行改变。

    • public static void setIn(InputStreamin)
    • public static void setOut(PrintStreamout)

练习: 从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作, 直至当输入“e”或者“exit”时,退出程序。

第一种方法:使用 Scanner类

第二种方法:使用 System.in System.in —> 转换流 —> BufferedReader的readLine()

public class OtherStreamsTest {
    /*
    *
    * 练习:
    * 从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,
    * 直至当输入“e”或者“exit”时,退出程序。
    * */
    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            // 转换流
            InputStreamReader isr = new InputStreamReader(System.in);
            // 缓冲输入流
          br  = new BufferedReader(isr);
            while (true) {
                String data = br.readLine();
                if ("e".equalsIgnoreCase(data) || "exit".equals(data)) {
                    System.out.println("程序退出");
                    break;
                }
                System.out.println(data.toUpperCase());
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

打印流

  • 实现将基本数据类型的数据格式转化为字符串输出

  • 打印流:PrintStream和PrintWriter

    • 提供了一系列重载的print()和println()方法,用于多种数据类型的输出

    • PrintStream和PrintWriter的输出不会抛出IOException异常

    • PrintStream和PrintWriter有自动flush功能

    • PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。在需要写入字符而不是写入字节的情况下,应该使用PrintWriter 类。

    • System.out返回的是PrintStream的实例

public class PrintStreamTest {
    @Test
    public void test2(){
        PrintStream ps = null;
        try {
            FileOutputStream fos = new FileOutputStream(new File("C:\\java\\JAVA_NOTES\\1.JavaSE\\笔记\\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();
            }
        }
    }
}

数据流

  • 为了方便地操作Java语言的基本数据类型String的数据,可以使用数据流。

  • 数据流有两个类:(用于读取和写出基本数据类型、String类的数据)

  • DataInputStream和DataOutputStream

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

DataInputStream中的方法

boolean readBoolean()	byte readByte()
char readChar()	float readFloat()
double readDouble()	short readShort()
long readLong()	int readInt()
String readUTF()	void readFully(byte[s] b)

DataOutputStream中的方法

​ 将上述的方法的read改为相应的write即可。

import org.junit.Test;
import java.io.*;

public class OtherStreamTest {    
   /**
     * 3.数据流
     *   3.1 DataInputStream 和 DataOutputStream
     *   3.2 作用:用于读取或写出基本数据类型的变量或字符串
     *
     *   练习:将内存中的字符串、基本数据类型的变量写出到文件中。
     *
     *   注意:处理异常的话,仍然应该使用try-catch-finally.
     */
    @Test
    public void test3() throws IOException {
        //1.
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
        //2.
        dos.writeUTF("刘刚");
        dos.flush();//刷新操作,将内存中的数据写入文件
        dos.writeInt(23);
        dos.flush();
        dos.writeBoolean(true);
        dos.flush();
        //3.
        dos.close();
    }

    /**
     * 将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。
     *
     * 注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!
     */
    @Test
    public void test4() throws IOException {
        //1.
        DataInputStream 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);

        //3.
        dis.close();

    }
}

对象流

对序列化的理解
  • ObjectInputStreamOjbectOutputSteam

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

  • 序列化:用ObjectOutputStream类保存基本类型数据或对象的机制

  • 反序列化:用ObjectInputStream类读取基本类型数据或对象的机制

  • ObjectOutputStreamObjectInputStream不能序列化statictransient修饰的成员变量

  • 对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。//当其它程序获取了这种二进制流,就可以恢复成原来的Java对象

  • 序列化的好处在于可将任何实现了Serializable接口的对象转化为字节数据,使其在保存和传输时可被还

  • 序列化是RMI(Remote Method Invoke –远程方法调用)过程的参数和返回值都必须实现的机制,而RMI 是JavaEE的基础。因此序列化机制是JavaEE平台的基础

  • 如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一。否则,会抛出NotSerializableException异常

    • Serializable
    • Externalizable

序列化/反序列化字符串:

  // 序列化:将内存中的 java 对象以二进制流的形式保存到硬盘上,或通过网络传输出去
    // ObjectOutputStream
    // 建议使用 try-catch-finally,我是为了省事。。
    @Test
    public void test() throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("test.bat")));
        // 将 string类型数据序列化到文件中
        oos.writeObject(new String("我爱中国"));

        oos.flush();

        oos.close();
    }
    // 反序列化;将硬盘上文件中的对象还原为内存中的java对象
    // ObjectInputStream。
    @Test
    public void test2() throws Exception {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("test.bat")));

        String s =(String) ois.readObject();

        System.out.println(s);
        
        ois.close();
    }

序列化/反序列化自定义对象:

要求自定义类实现 Serializable 接口,并定义序列化版本号 serialVersionUID

User类

public class User implements Serializable {
    // 序列化号:该类的标识、
    private static final long serialVersionUID = 23664543L;
    private String name;
    private int age ;

    public User() {
    }

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

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

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

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

序列化、反序列化过程

  @Test
    public void test() throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("test.bat")));
        // 将 string类型数据序列化到文件中
        // oos.writeObject(new String("我爱中国"));
        // 序列化自定义类
        oos.writeObject(new User("lisi",22));
        oos.flush();

        oos.close();
    }
    // 反序列化;将硬盘上文件中的对象还原为内存中的java对象
    // ObjectInputStream。
    @Test
    public void test2() throws Exception {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("test.bat")));

        // String s =(String) ois.readObject();
        User user = (User) ois.readObject();
        System.out.println(user);

        ois.close();
    }
serialVersionUID 的理解

凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态常量:

  • private static final long serialVersionUID;

  • serialVersionUID用来表明类的不同版本间的兼容性。简言之,其目的是以序列化对象进行版本控制,有关各版本反序列化时是否兼容。

  • 如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自动生成的。若类的实例变量做了修改,serialVersionUID可能发生变化。故建议,显式声明。

简单来说,Java的序列化机制是通过在运行时判断类的 serialVersionUID 来验证版本一致性的。在进行反序列化时,JVM会把传来的字节流中的 serialVersionUID 与本地相应实体类的 serialVersionUID 进行比较,如果相同就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异常。(InvalidC astException)

随机存储文件流

  • RandomAccessFile 声明在java.io包下,但直接继承于java.lang.Object类。并且它实现了DataInput、DataOutput这两个接口,也就意味着这个类既可以读也可以写
  • 构造器
    • public RandomAccessFile(Filefile, Strin gmode)
    • public RandomAccessFile(Stringname, String mode)
  • 创建RandomAccessFile类实例需要指定一个mode 参数,该参数指定RandomAccessFile的访问模式:
    • r: 以只读方式打开
    • rw:打开以便读取和写入
    • rwd:打开以便读取和写入;同步文件内容的更新
    • rws:打开以便读取和写入;同步文件内容和元数据的更新
  • 如果模式为只读r。则不会创建文件,而是会去读取一个已经存在的文件,如果读取的文件不存在则会出现异常。如果模式为rw读写。如果文件不存在则会去创建文件,如果存在则不会创建。

如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建。 如果写出到的文件存在,则会对原有文件内容进行覆盖。(默认情况下,从头覆盖)

    @Test
    public void test2() throws IOException {

        RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");

        raf1.write("xyz".getBytes());

        raf1.close();

    }

RandomAccessFile 对象包含一个记录指针,用以标示当前读写处的位置。RandomAccessFile类对象可以自由移动记录指针:

  • long getFilePointer():获取文件记录指针的当前位置
  • void seek(long pos):将文件记录指针定位到pos位置
    @Test
    public void test2() throws IOException {

        RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");

        // 将指针跳到角标为3的位置上
        raf1.seek(3);
        raf1.write("xyz".getBytes());

        raf1.close();

    }

NIO.2中Path、Paths、Files类的使用

  • Java NIO (New IO,Non-Blocking IO)是从Java 1.4版本开始引入的一套新的IO API,可以替代标准的Java IO API。NIO与原来的IO有同样的作用和目的,但是使用的方式完全不同,NIO支持面向缓冲区的(IO是面向流的)、基于通道的IO操作。NIO将以更加高效的方式进行文件的读写操作。

  • Java API中提供了两套NIO,一套是针对标准输入输出NIO,另一套就是网络编程NIO

  • 随着JDK 7 的发布,Java对NIO进行了极大的扩展,增强了对文件处理和文件系统特性的支持,以至于我们称他们为NIO.2。因为NIO 提供的一些功能,NIO已经成为文件处理中越来越重要的部分。

  • 早期的Java只提供了一个File类来访问文件系统,但File类的功能比较有限,所提供的方法性能也不高。而且,大多数方法在出错时仅返回失败,并不会提供异常信息。

  • NIO. 2为了弥补这种不足,引入了Path接口,代表一个平台无关的平台路径,描述了目录结构中文件的位置。Path可以看成是File类的升级版本,实际引用的资源也可以不存在。

在以前IO操作都是这样写的:

import java.io.File;

File file = new File(“index.html”);

但在Java7 中,我们可以这样写:

import java.nio.file.Path;
import java.nio.file.Paths;
Path path = Paths.get(“index.html”);
  • 同时,NIO.2在java.nio.file包下还提供了Files、Paths工具类,Files包含了大量静态的工具方法来操作文件;Paths则包含了两个返回Path的静态工厂方法。
  • Paths类提供的静态get()方法用来获取Path对象:
    • static Pathget(String first, String … more) : 用于将多个字符串串连成路径
    • static Path get(URI uri): 返回指定uri对应的Path路径

Path 接口

img

FIles类

img

img

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鲨瓜2号

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值