谨个人学习 Java IO 历程

开篇先放一张图

初步了解 输入流 与 输出流 。

将txt文本文件内容 展示到程序中,这是输入。例如将aaa.txt 内容打印在 看控制台 。

在程序中预先设置一些数据 ,传输到aaa.txt 中,这是输出 ,例如将 “hello world” 保存到aaa.txt中 ,

image-20201207173200079

正片即将到来,内容引起不适。🙅


java IO 中常用的类

在 java.io 包中最重要的就是 五个类 和 一个接口 ,五个类 指的是 :

File、OutputStream 、InputStream 、Writer 、Reader

一个接口指的是 Serializable 。掌握了 IO 的核心操作 ,那么对应Java IO 体系就有了初步认识 。

  • 1、File (文件特征与管理) :用于文件或目录的描述信息 ,例如生成新目录 、修改文件名、删除文件 、判断文件所在路径等 。
  • 2、OutputStream (二进制格式操作) :抽象类 ,基于字节的输出操作 ,是所有输出流的父类 。定义了所有输出流都具有的共同特征 。
  • 3、InputStream (二进制格式操作) :抽象类 。基于字节的输入操作 ,是所有输入流的父类 。定义了所有输入流都具有的共同特征。
  • 4、Reader (文件格式操作) :抽象类 。基于字符的输入操作 。
  • 4、Writer (文件格式操作) :抽象类 。基于字符的输出操作 。

IO 体系结构图 :

IO流


Java的 I/O 操作大概可以分为这几类:

  • 磁盘操作:File
  • 字节操作:InputStream 和 OutPutStream
  • 字符操作:Reader 和 Writer
  • 对象操作:Serializable
  • 网络操作:Socket
  • 新的输入/输出:NIO

File

文件操作步骤流程:

  • 1、使用File类打开一个文件

  • 2、通过字节流或者字符流的子类,指定输出位置

  • 3、进行读写操作

  • 4、关闭输入输出流

该类主要用于获取文件和目录的属性,文件和目录的创建、查找、删除、重命名等,但不能对文件进行读写操作。

File对象代表磁盘中实际存在的文件和目录。


File 类的使用:常用构造器

构造器 作用
public File(String pathname) 以pathname为路径创建File对象,可以是 绝对路径或者相对路径
      绝对路径:是一个固定的路径,从盘符开始
      相对路径:是相对于某个位置开始,默认的当前路径在系统属性user.dir中存储
public File(String parent,String child) 以parent为父路径,child为子路径创建File对象。
public File(File parent,String child) 根据一个父File对象和子文件路径创建File对象
  • 1、以pathname为路径创建File对象
File dir1 = new File("D:/IOTest/dir1");
  • 2、// 创建以dir1为父目录,名为"dir2"的File对象
File dir2 = new File(dir1, "dir2");
  • 3、// 创建以dir2为父目录,名为"test.txt"的File对象
File file = new File(dir2, "test.txt");

File 类的使用:路径分隔符

public static final String separator // 根据操作系统,动态的提供分隔符
    // D:\\yuanwu\\info.txt
File file = new File("D:" + File.separator + "yuanwu" + File.separator + "info.txt");

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数组
File 类的重命名功能
public boolean renameTo(File dest) 把文件重命名为指定的文件路径
File类的判断功能
public boolean isDirectory() 判断是否时文件目录
public boolean isFile() 判断是否是文件
public boolean exists() 判断是否存在
public boolean canRead() 判断是否可读
public boolean canWrite() 判断是否可写
public boolean isHidden() 判断是否隐藏
File类的创建功能
public boolean createNewFile() 创建文件。若文件存在,则不创建,返回false 。
public boolean mkdir() 创建文件目录。
如果此文件目录存在 ,则不创建
如果此文件目录的上层目录不存在 ,也不创建 。
public boolean mkdirs() 创建文件目录 。如果上传文件目录不存在 ,一并创建
File类的删除功能
public boolean mkdirs() 删除文件或者文件夹

创建注意事项 :如果创建文件或者文件目录没有指定盘符路径 ,默认在项目路径下 。

删除注意事项 :Java 中File类的删除不走回收站 ,要删除一个文件目录 ,请注意该文件目录不能包含文件或者文件目录 。


流的原理及流的分类

抽象基类 节点流(文件流) 缓冲流(处理流的一种)
InputStream (字节输入流,读入数据) FileInputStream (处理字节) BufferedInputStream
OutputStream (字节输出流,写出数据) FileOutputStream (处理字节) (byte[] b) BufferedOutputStream
Reader (字符输入流,读入数据) FileReader (处理字符) BufferedReader
Writer (字符输入流,写出数据) FileWriter (处理字符) (char[] c) BufferedWriter

什么情况下使用哪种流呢?

如果数据所在的文件通过windows自带的记事本打开并能读懂里面的内容,就用字符流,其他用字节流。

如果你什么都不知道,就用字节流。


image-20201207172619170

在Java程序中所有的 数据都是以流的方式进行传输或者保存的,程序需要数据的时候使用输入流读取数据,当程序需要将一些数据保存起来则使用输出流。流中保存的实际上是字节文件。

如果数据的流向从程序到设备,成为输出流,反之输入流

  • 按操作数据类型分为:字符流(16 bit),字节流(8 bit)
  • 按数据流的流向分为:输入流 ,输出流
  • 按流的角色可分为 :节点流,处理流

所有的文件在硬盘传输时都是以字节的方式进行的,按字节的方式存储,字符只有在内存中才会形成

字节流

字节流处理数据的基本单元是单个字节(byte),通常用来处理二进制数据

抽象基类:

InputStream,OutputStream,(字节流)

字节流在操作的时候不会用到缓冲区(内存),是直接对文件本身操作的

字符流

Java中字符流处理数据的基本单元是2字节Unicode码元(char),通常用来处理文本数据

抽象基类:

Reader,Writer,(字符流)

字符流在操作的时候会使用到缓冲区


image-20201207173200079


image-20201207173416799


InputStream & Reader

  • InputStream 和 Reader 是所有输入流的基类
  • InputStream (典型实现 :FileInputStream
    • int read()
    • int read(byte[] b)
    • int read(byte[] b, int off, int len)
  • Reader (典型实现 :FileReader
    • int read()
    • int read(byte[] b)
    • int read(byte[] b, int off, int len)
  • 打开的 IO 资源需要显示的关闭 IO 资源
  • FileInputStream 读取非文本数据的原始字节流 。
  • FileReader 读取字符流 文本数据 。
InputStream
  • int read()

从输入流中读取数据的下一个字节。返回 0 到 255 范围内的 int 字节值。如果因为已经到达流末尾而没有可用的字节,则返回值 -1

  • int read(byte[] b)

从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。如果因为已经到达流末尾而没有可用的字节,则返回值 -1。否则以整数形式返回实际读取的字节数

  • int read(byte[] b, int off, int len)

将输入流中最多 len 个数据字节读入 byte 数组。尝试读取 len 个字节,但读取的字节也可能小于该值。以整数形式返回实际读取的字节数。如果因为流位于文件末尾而没有可用的字节,则返回值 -1

  • public void close() throws IOException

关闭此输入流,释放资源

Reader
  • int read()

读取单个字符。作为整数 读取的字符,范围在 0-65535 之间 (0x00=0xffff) (两个字节的 Unicode码),如果已达到流的末尾 ,返回-1.

  • int read(byte[] b)

将字符读入数组。如果已到达流的末尾,则返回 -1。否则返回本次读取的字符数

  • int read(byte[] b, int off, int len)

将字符读入数组的某一部分。存到数组cbuf中,从off处开始存储,最多读len个字符。如果已到达流的末尾,则返回 -1。否则返回本次读取的字符数

  • public void close() throws IOException

关闭此输入流,释放资源


OutputStream & Writer

OutputStream 和 Writer 是所有输出流的基类

  • void write(int b);
  • void write(byte[] b);
  • void write(byte[] b, int off, int len);
  • void flush();
  • void close(); 先刷新 ,在关闭输出流 。

字符流直接以字符作为操作单位 ,Writer 可以用字符串来代替字符数组 。使用 String 对象作为参数 。

  • void writer(String str);
  • void writer(String str, int off, int len);

FileOutputStream 用于写出非文本数据的原始字节流 。

FileWriter 用于写出字符流 。


OutputStream
  • void write(int b)
    将指定的字节写入此输出流。write 的常规协定是:向输出流写入一个字节。要写入的字节是参数 b 的八个低位。b 的 24 个高位将被忽略。 即写入0~255范围的。
  • void write(byte[] b)
    将 b.length 个字节从指定的 byte 数组写入此输出流。write(b) 的常规协定是:应该与调用 write(b, 0, b.length) 的效果完全相同。
  • void write(byte[] b,int off,int len)
    将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。
  • public void flush()throws IOException
    刷新此输出流并强制写出所有缓冲的输出字节,调用此方法指示应将这些字节立即写入它们预期的目标。
  • public void close() throws IOException
    关闭输出流并释放系统资源。

Writer
  • void write(int c)
    写入单个字符。要写入的字符包含在给定整数值的 16 个低位中,16 高位被忽略。 即写入0 到 65535 之间的Unicode码。

  • void write(char[] cbuf)
    写入字符数组。

  • void write(char[] cbuf,int off,int len)
    写入字符数组的某一部分。从off开始,写入len个字符

  • void write(String str)
    写入字符串。

  • void write(String str,int off,int len)
    写入字符串的某一部分。

  • void flush()
    刷新该流的缓冲,则立即将它们写入预期目标。

  • public void close() throws IOException

    关闭输出流并释放系统资源。



节点流和处理流

节点流 :

直接从数据源或目的地读写数据

image-20201207173650839

  • 节点流(文件流)

读取文件

1、建立一个流对象 ,将已存在的一个文件加载进流 。

FileReader file = new FileReader(new File("D:\\Test.txt"));

2、创建一个临时存放数据的数组 。

Char[] b = new char[1024];

3、调用流对象的读取方法将流中的数据读入到数组中 。

file.read(b);

4、关闭资源 。

file.close();

示例 :

@Test
public void test07() throws IOException {
    FileReader fileReader = null;
    try {
        fileReader = new FileReader(new File("G:\\aaa.txt"));
        char[] buff = new char[1024];
        int len;
        while ((len = fileReader.read(buff)) != -1) {
            System.out.println(new String(buff, 0, len)); // AAAAABBBBCCC
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        fileReader.close();
    }
}

写入文件

1、创建流对象 ,建立数据存放文件

FileWriter fw = new FileWriter("G:\\aaa.txt");

2、调用流对象的写入方法 ,将数据写入流 。

fw.write("yuanwu"); // 会清空文件原有的数据 

3、关闭流资源 。并将流中的数据清空到文件中 。

fw.close();

示例 :

@Test
public void test07() throws IOException {
    FileWriter fileWriter = null;
    try {
        fileWriter = new FileWriter(new File("G:\\aaa.txt"));
        fileWriter.write("yuanwu");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        fileWriter.close();
    }
}

写入注意事项 :如果不希望原有的数据被覆盖 ,在构造器参数增加 true,在文件内容末尾追加内容 。

fileWriter = new FileWriter(new File("G:\\aaa.txt"),true);

在读取文件时 ,必须保证该文件已存在,否则报异常 。

  • 温馨提示

字节流操作字节 :.mp3、.avi、.rmvb、.mp4、.jpg、.ppt、.doc

字符流操作字符 :只能操作普通文本文件 .txt、.java、.c、等。word 、excel、 ppt 不是文本文件 。


FileInputStream 读数据

@Test
public void test11() {
    FileInputStream fis = null;
    try {
        // 造文件
        File file = new File("G:\\aaa.txt");
        // 造流
        fis = new FileInputStream(file);
        // 读数据
        byte[] buffer = new byte[100];
        int len ; // 记录每次读取的字节的个数
        while ((len = fis.read(buffer)) != -1) {
            String s = new String(buffer, 0, len);
            System.out.println(s);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭资源 
        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

FileOutputStream 写数据

@Test
public void test12() {
    FileOutputStream fos = null;
    // 造文件
    File file = new File("G:\\aaa.txt");
    try {
        // 造流(字节输出流) 参数 true ,不会覆盖原有的内容 。
        fos = new FileOutputStream(file,true);
        fos.write(98); // 写入字节数据 小写b
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭资源 
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

FileInputStream & FileOutputStream :操作图片案例(复制图片)

示例

@Test
public void test10() {
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        // 1、创建 File 类的对象,指明读入和写出的文件
        File file1 = new File("xxx.png");
        File file2 = new File("aaa.png");
        // 2、创建输入流和输出流的对象 (操作字节)
        fis = new FileInputStream(file1);
        fos = new FileOutputStream(file2);
		// 3、数据的读入和写出操作 
        byte[] buf = new byte[1024];
        int len; // 记录每次读入到 buf数组的字节的个数
        while ((len = fis.read(buf)) != -1) {
            // 每次写出 len 个字节
            fos.write(buf, 0, len);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 4、关闭流资源 
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

处理流 :

列举三种常用处理流 。

目的 :提高文件的读写效率 。

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

image-20201207173902152

处理流之一 :缓冲流
  • 使用缓冲流时 ,会创建一个内部缓冲区数组,缺省使用 8192个字节(8kb) 的缓冲区 。

  • 使用缓冲流要 “套接” 在相应的节点流上 。根据数据操作类型可分为如下几种 :

    • BufferedInputStream 和 BufferedOutputStream
    • BufferedReader 和 BufferedWriter

BufferedInputStream

字节缓冲输入流

  • 当使用 BufferedInputStream 读取字节文件时,BufferedInputStream 会一次性从文件中读取 8192 个字节(8Kb),放在缓冲区中,直到缓冲区满了才重新从文件中读取下一个 8192 个字节数组 。

  • 向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区满,BufferedInputStream 才会把缓冲区中的数据一次性写到文件里,使用 flush() 方法可以强制将缓冲区的内容全部写入输出流 。

  • flush() 方法的使用 :手动将 buffer 中内容写入文件里。

BufferedOutputStream

字节缓冲输出流

BufferedInputStream 和 BufferedOutputStream 案例 :实现非文本文件的复制

@Test
public void test13() {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        // 造文件
        File srcFile = new File("G:\\aaa.txt");
        File destFile = new File("G:\\aaa1.txt");
        // 造流
        // 字节流
        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);
        // 缓冲流
        bis = new BufferedInputStream(fis);
        bos = new BufferedOutputStream(fos);
        // 复制的细节 :读取、写入
        byte[] buffer = new byte[1024];
        int len;
        while ((len = bis.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭流资源 
        try {
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            bis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

BufferedReader

BufferedReader是为了提供读的效率而设计的一个包装类,可以包装字符流。可以从字符输入流读取文本,缓冲各个字符,从而实现高效读取

BufferedWriter

字符缓冲输出流,把数据写入到文件

  • 使用缓冲区将字节缓冲到内存中,比从硬盘读取的效率要高

示例 :

将 aaa.txt 文件的内容写入到 bbb.txt .但是写入的内容 会将 bbb.txt原有的内容覆盖掉 。

@Test
public void test08() throws IOException {
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
        // 创建缓冲流对象,它是处理流,对节点流的包装
        br = new BufferedReader(new FileReader("G:\\aaa.txt"));
        bw = new BufferedWriter(new FileWriter("G:\\bbb.txt"));
        /* 方式一 :
          char[] buff = new char[1024];
          int len;
          while ((len = br.read(buff)) != -1) {
          		bw.write(buff,0,len);
          }
        */
        String str = "";	
        // 一次读取字符文本文件的一行字符
        while ((str = br.readLine()) != null) {
            bw.write(str); // 一次写入一行字符串
            bw.newLine(); // 写入分隔符
        }
        // 刷新缓冲区,手动将 bw 中内容写入文件里
        bw.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        bw.close(); // 关闭流 
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

缓冲流案例 :字符在文件中出现的个数
@Test
public void test14() {
    FileReader fr = null;
    BufferedWriter bw = null;
    Map<Character, Integer> map = new HashMap<>();
    try {
        fr = new FileReader("G:\\aaa.txt");
        int len = 0;
        while ((len = fr.read()) != -1) {
            char c = (char) len;
            // 判断 字符是否在map中第一次出现 。
            if (map.get(c) == null) {
                map.put(c, 1);
            } else {
                map.put(c, map.get(c) + 1);
            }
        }
        // 把map中数据存在ccc.txt
        // 创建流
        bw = new BufferedWriter(new FileWriter("G:\\ccc.txt"));
        // 遍历 map,再写入数据
        Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
        for (Map.Entry<Character, Integer> entry : entrySet) {
            switch (entry.getKey()) {
                    // 特殊符号 
                case ' ':
                    bw.write( "空格=" + entry.getValue());
                    break;
                case '\t':
                    bw.write("tab=" + entry.getValue());
                    break;
                case '\n':
                    bw.write("换行=" + entry.getValue());
                    break;
                case '\r':
                    bw.write("回车=" + entry.getValue());
                    break;
                    // 字符
                default:
                    bw.write(entry.getKey() + "=" + entry.getValue());
                    break;
            }
            bw.newLine();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


节点流之二 :转换流

属于字符流 。

解码 :字节、字节数组——>字符数组、字符串 InputStreamReader

编码 :字符数组 、字符串——> 字节、字节数组 OutputStreamWriter

转换流提供 字节流和字符流之间的相互转换 。字节流中的数据都是字符时,转成字符流操作更高效 。

InputStreamReader:将InputStream转换为Reader

OutputStreamWriter:将Writer转换为OutputStream

使用转换流来处理文件乱码问题,实现编码和解码功能 。


InputStreamReader

  • 实现将字节的输入流转换为字符的输入流 (按指定字符集)
  • 需要和 InputStream “套接”
  • 构造器
public InputStreamReader(InputStream in)
public InputStreamReader(InputStream in, String charsetName)

例子 :Reader isr = new InputStreamReader(System.in, "UTF-8");


OutputStreamWriter

  • 实现将字符的输出流转换为字节的输出流 (按指定字符集)
  • 需要和 OutputStream "套接"
  • 构造器
public OutputStreamWriter(OutputStream out)
public OutputSreamWriter(OutputStream out,String charsetName)

例子 :Writer wri = new OutPutStreamWriter(System.out, "GBK");


image-20201208103447372

示例 :

FileInputStream :是InputStream具体实现类 ,文件字节输入流 ,对文件数据以字节的形式进行读取操作 。

FileOutputStream :是OutputStream具体实现类,文件字节输出流 ,用于将数据写入到文件中 。第二个参数传 true ,则写入的数据是从末尾追加内容 。

InputStreamReader :需要和 InputStream “套接”,(传入InputStream 实现类 FileInputStream ,再传入字符编码 )。

OutputStreamWriter :需要和 OutputStream “套接”,(传入OutputStream 实现类 OutputStreamWriter ,再传入字符编码) 。

BufferedReader , BufferedWriter :缓冲流 。

示例一 :将 GBK 格式数据 以 GBK/UTF-8 写出

@Test
public void test09() throws Exception {
    // 造文件、造流
    FileInputStream fileInputStream = new FileInputStream("G:\\aaa.txt");
    FileOutputStream fileOutputStream = new FileOutputStream("G:\\bbb.txt");
   
    // 解码过程 读入
    InputStreamReader gbk = new InputStreamReader(fileInputStream, "GBK"); 
    // 编码过程 写出
    OutputStreamWriter gbk1 = new OutputStreamWriter(fileOutputStream, "GBK"); 
    
    BufferedReader bufferedReader = new BufferedReader(gbk); 
    BufferedWriter bufferedWriter = new BufferedWriter(gbk1); 
    // 读写过程
    String str = null;
    while ((str = bufferedReader.readLine()) != null) {
        bufferedWriter.write(str);
        bufferedWriter.newLine();
        bufferedWriter.flush();
    }
    // 关闭资源 
    bufferedWriter.close();
    bufferedReader.close();
}

示例二 :将数据在控制台中打印

解码操作 :字节、字节数组——>字符数组、字符串 InputStreamReader

@Test
public void test15() {
    try {
        FileInputStream fis = new FileInputStream("G:\\aaa.txt");
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        char[] buff = new char[20];
        int len ;
        while ((len = isr.read(buff)) != -1) {
            String s = new String(buff, 0, len);
            System.out.println(s);
        }
        isr.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }
}

处理流之三 :对象流

简介 :

  • ObjectInputStream和OjbectOutputSteam
  • 用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
  • 序列化:用ObjectOutputStream 类保存基本类型数据或对象的机制
  • 反序列化:用ObjectInputStream 类读取基本类型数据或对象的机制
  • ObjectOutputStream和ObjectInputStream不能序列化static和transient修 饰的成员变量
  • 对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从 而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传 输到另一个网络节点。//当其它程序获取了这种二进制流,就可以恢复成原 来的Java对象

自定义类序列化 需实现 Serializable 接口,这个接口是个空方法接口 ,用于标识 ,并且 还要加上 UID。模板如下 :

private static final long serialVersionUID = 6805652262626734654L;


案例 :序列化

@Test
public void test01() {
    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(new FileOutputStream("G:\\aaa1.dat"));
        // oos.writeObject(new Person("张三,18,"男","董事长"));
        oos.writeUTF(new String("我爱中国"));
        oos.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            oos.close();
        } catch (IOException e) {
        }
    }
}

案例 :反序列化

@Test
    public void test02() {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("G:\\aaa1.dat"));
            // Object obj = ois.readObject();
            // String str = (String)obj;
            String readUTF = ois.readUTF();
            System.out.println(readUTF); // 我爱中国
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

其实往后面 ,用到的都是现成的 序列化和反序列化 ,JSON 格式 "{"name":"Tom"}" ......



常用流的基本应用小结

  • 流是用来处理数据的
  • 处理数据时,一定要先明确 数据源,与数据目的
    • 数据源可以是文件中,可以是键盘
    • 数据目的地可以是文件、显示器 或其他设备 。
  • 流只是在帮助数据进行传输,并对传输的数据进行处理。如:过滤数据、转换数据等等。

NIO 概述

NIO 是从 java 1.4 版本引入的 IO API 。NIO与原来的IO有同样的作用和目的,但使用方式不同。NIO支持面向缓冲区 (IO时面向流) 、基于通道的IO操作,NIO 更加高效的方式进行文件的读写操作 。

针对标准输入输出NIO ,网络编程NIO 。

核心API

Path、Paths、Files ,核心API 。

Files 包含大量的静态工具方法来操作文件 ;

Paths 包含了两个返回 Path 的静态工厂方法 。

Java 7 之前 语法 :

import java.io.File;
File file = new File("xxx.txt");

Java 7 之后的语法 :

import java.nio.file.Path;
import java.nio.file.Paths;
Path path = Paths.get("xxx.txt");

  • Paths 类提供的静态 get() 方法用来获取 Path 对象 。
方法名称 作用
public static Path get(String first, String... more) 用于将多个字符串 串连成路径 。
public static Path get(URI uri) 返回指定 uri 对应的 Path 路径

  • Path 接口 常用方法
方法名称 作用
String toString 返回调用 Path 对象的字符串表示形式
boolean startsWith(String path) 判断是否以 path 路径开始
boolean endsWith(String path) 判断是否以 path 路径结束
boolean isAbsolute() 判断是否是绝对路径
Path getParent() 返回Path对象包含整个路径,不包含 Path 对象指定的文件路径
Path getRoot() 返回调用 Path 对象的根路径
Path getFileName() 返回与调用 Path 对象关联的文件名
int getNameCount() 返回Path 根目录后面元素的数量
Path getName(int idx) 返回指定索引位置 idx 的路径名称
Path toAbsolutePath() 作为绝对路径返回调用 Path 对象
Path resolve(Path p) 合并两个路径,返回合并后的路径对应的Path对象
File toFile() 将Path转化为File类的对象

  • Files 类的常用方法

java.nio.file.Files 用于操作文件或目录的工具类 。

方法名称 作用
static Path copy(Path source, Path target, CopyOption... options) 文件复制
static Path createDirectory(Path dir, FileAttribute<?>... attrs) 创建一个目录
static Path createFile(Path path, FileAttribute<?>... attrs) 创建一个文件
static void delete(Path path) 删除一个文件/目录,不存在则报错
static boolean deleteIfExists(Path path) Path 对应的文件/目录若存在,执行删除
static Path move(Path source, Path target, CopyOption... options) 将 source 移动到 target位置
static long size(Path path) 返回 path 指定文件的大小
  • Files 类常用方法 :用于判断
方法名称 作用
boolean exists(Path path, LinkOption … opts) 判断文件是否存在
boolean isDirectory(Path path, LinkOption … opts) 判断是否为目录
boolean isRegularFile(Path path, LinkOption … opts) 判断是否是文件
boolean isHidden(Path path) 判断是否是隐藏文件
boolean isReadable(Path path) 判断文件是否可读
boolean isWritable(Path path) 判断文件是否可写
boolean notExists(Path path, LinkOption … opts) 判断文件是否不存在
  • Files 类的常用方法 :用于操作内容
方法名称 作用
static SeekableByteChannel newByteChannel(Path path, OpenOption... options) 获取与指定文件的连接
options 为指定打开方式
static DirectoryStream newDirectoryStream(Path dir) 打开 dir 指定的目录
static InputStream newInputStream(Path path, OpenOption... options) 获取 InputStream 对象
static OutputStream newOutputStream(Path path, OpenOption... options) 获取 OutputStream 对象

posted @ 2020-12-08 20:07  san只松鼠  阅读(109)  评论(0)    收藏  举报