Java笔记035-IO流/文件、常用的文件操作、IO流原理及流的分类、IO流体系图-常用的类

目录

IO流

文件

什么是文件

文件流

常用的文件操作

创建文件对象相关构造器的方法

创建文件对象相关构造器和方法

获取文件的相关信息

应用案例

目录的操作和文件删除

应用案例

IO流原理及流的分类

Java IO流原理

流的分类

IO流体系图-常用的类

IO流体系图

InputStream:字节输入流

FileInputStream介绍

FileInputStream应用实例

FileOutputStream介绍

FileOutputStream应用实例1

FileOutputStream应用实例2

​编辑FileReader和FileWriter介绍

FileReader相关方法:

FileWriter常用方法

FileReader和FileWriter应用案例 


IO流

文件

什么是文件

文件是保存数据的地方,比如word文档,txt文本,excel表格...都是文件,它既可以保存一张图片,也可以保存视频,声音等

文件流

文件在程序中是以流的形式来操作的

 流:数据在数据源(文件)和程序(内存)之间经历的路径

输入流:数据从数据源(文件)到程序(内存)的路径

输出流:数据从程序(内存)到数据源(文件)的路径

常用的文件操作

创建文件对象相关构造器的方法

相关方法

new File(String pathname);//根据路径构建一个File对象
new File(File parent, String child);//根据父目录文件+子路径构建
new File(String parent, String child);//根据父目录+子路径构建

createNewFile//创建新文件

创建文件对象相关构造器和方法

应用案例演示

  • 请在E盘下,创建文件news1.txt、news2.txt、news3.txt,用三种不同的方式创建
package com19.file;

import org.junit.jupiter.api.Test;

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

/**
 * @author 甲柒
 * @version 1.0
 * @title FileCreate
 * @package com19.file
 * @time 2023/3/31 9:37
 * 演示创建文件
 */
public class FileCreate {
    public static void main(String[] args) {

    }

    //方式1 new File(String pathname);//根据路径构建一个File对象
    @Test
    public void create01() {
        String filePath = "E:\\news1.txt";
        File file = new File(filePath);

        try {
            file.createNewFile();
            System.out.println("文件 news1.txt 创建成功~~~");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //方式2 new File(File parent, String child);//根据父目录文件+子路径构建
    //E:\\news.txt
    @Test
    public void create02() {
        File parentFile = new File("E:\\");
        String fileName = "news2.txt";
        //这里的file对象,在Java程序中,只是一个对象
        //只有执行了createNewFile 方法,才会真正的,在磁盘创建该文件
        File file = new File(parentFile, fileName);
        try {
            file.createNewFile();
            System.out.println("文件 news2.txt 创建成功~~~");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //方式3 new File(String parent, String child);//根据父目录+子路径构建
    @Test
    public void create03() {
        String parentPath = "E:\\";
        String filePath = "news3.txt";
        File file = new File(parentPath, filePath);
        try {
            file.createNewFile();
            System.out.println("文件 news3.txt 创建成功~~~");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

获取文件的相关信息

getName、getAbsolutePath、getParent、length、exists、isFile、isDirectory

应用案例

如何获取文件的大小,文件名,路径,父File,是文件还是目录(目录本质也是文件,一种特殊的文件),是否存在

package com19.file;

import org.junit.jupiter.api.Test;

import java.io.File;

/**
 * @author 甲柒
 * @version 1.0
 * @title FileInformation
 * @package com19.file
 * @time 2023/3/31 10:06
 */
public class FileInformation {
    public static void main(String[] args) {

    }

    //获取文件的信息
    @Test
    public void info() {
        //先创建文件对象
        File file = new File("E:\\news1.txt");

        //调用相应的方法,得到对应信息
        System.out.println("文件名=" + file.getName());
        //getName、getAbsolutePath、getParent、length、exists、isFile、isDirectory
        System.out.println("文件绝对路径=" + file.getAbsolutePath());
        System.out.println("文件父级路径=" + file.getParent());
        System.out.println("文件大小(字节)=" + file.length());//hello甲柒   11个字节
        System.out.println("文件是否存在=" + file.exists());//true
        System.out.println("文件是否是一个文件=" + file.isFile());//true
        System.out.println("文件是否是一个目录=" + file.isDirectory());//false
    }
}

目录的操作和文件删除

mkdir创建一级目录、mkdirs创建多级目录、delete删除空目录或文件

应用案例

  1. 判断E:\\news1.txt 是否存在,如果存在就删除
  2. 判断E:\\demo02 是否存在,存在就删除,否则提示不存在
  3. 判断E:\\demo\\a\\b\\c 目录是否存在,如果存在就提示已经存在,否则就创建
package com19.file;

import org.junit.jupiter.api.Test;

import java.io.File;

/**
 * @author 甲柒
 * @version 1.0
 * @title Directory
 * @package com19.file
 * @time 2023/3/31 10:22
 */
public class Directory {
    public static void main(String[] args) {

    }

    //判断E:\\news1.txt 是否存在,如果存在就删除
    @Test
    public void m1() {
        String filePath = "E:\\news1.txt";
        File file = new File(filePath);
        if (file.exists()) {//如果文件存在
            if (file.delete()) {//删除该文件并提示
                System.out.println(filePath + " 删除成功~~~");
            } else {
                System.out.println(filePath + " 删除失败!!!");
            }
        } else {
            System.out.println(filePath + " 文件不存在~~~");
        }
    }

    //判断E:\\ 是否存在,存在就删除,否则提示不存在
    //在Java编程中,目录也被当成文件
    @Test
    public void m2() {
        String filePath = "E:\\demo02";
        File file = new File(filePath);
        if (file.exists()) {//如果文件存在
            if (file.delete()) {//删除该文件并提示
                System.out.println(filePath + " 删除成功~~~");
            } else {
                System.out.println(filePath + " 删除失败!!!");
            }
        } else {
            System.out.println(filePath + " 目录不存在~~~");
        }
    }

    //判断E:\\demo\\a\\b\\c 目录是否存在,如果存在就提示已经存在,否则就创建
    @Test
    public void m3() {
        String directoryPath = "E:\\demo\\a\\b\\c";
        File file = new File(directoryPath);
        if (file.exists()) {//如果文件存在
            //提示该文件存在
            System.out.println(directoryPath + " 文件存在~~~");
        } else {//创建该文件
            if (file.mkdirs()) {
                System.out.println(directoryPath + " 文件创建成功~~~");
            } else {
                System.out.println(directoryPath + " 文件创建失败~~~");
            }
        }
    }
}

IO流原理及流的分类

Java IO流原理

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

流的分类

  • 按操作数据单位不同分为:字节流(8 bit),字符流(按字符)
  • 按数据流的流向不同分为:输入流,输出流
  • 按流的角色的不同分为:节点流,处理流/包装流

抽象基类

字节流 字符流
输入流 InputStream Reader
输出流 OutputStream Writer
  1. Java的IO流共涉及40多个类,实际上非常规则,都是从如上4个抽象基类派生的
  2. 由这四个类派生出来的子类名称都是以其父类名作为子类名后缀

IO流体系图-常用的类

  1. IO流体系图

  2. 文件VS流

InputStream:字节输入流

InputStream抽象类是所有类字节输入流的超类

InputStream常用的子类

  1. FileInputStream:文件输入流
  2. BufferedInputStream:缓冲字节输入流
  3. ObjectInputStream:对象字节输入流

FileInputStream介绍

FileInputStream应用实例

要求:请使用FileInputStream读取hello.txt文件,并将文件内容显示到控制台

package com19.inputstream_;

import org.junit.jupiter.api.Test;

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

/**
 * @author 甲柒
 * @version 1.0
 * @title FileInputStream_
 * @package com19.inputstream_
 * @time 2023/3/31 18:55
 * 演示FileInputStream的使用(字节输入流 文件--》程序)
 */
public class FileInputStream_ {
    public static void main(String[] args) {

    }

    /**
     * 演示读取文件~~~
     * 单个字节的读取,效率比较低
     * 优化-》使用read(byte[] b)
     */
    @Test
    public void readFile01() {
        String filePath = "E:\\hello.txt";
        int readData = 0;
        FileInputStream fileInputStream = null;
        try {
            //创建FileInputStream 对象,用于读取 文件
            fileInputStream = new FileInputStream(filePath);
            //从该输入流读取一个字节的数据。如果没有输入可用,此方法将阻止
            //如果返回-1,表示读取完毕
            while ((readData = fileInputStream.read()) != -1) {
                System.out.print((char) readData);//转成char显示
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 使用read(byte[] b) 读取文件,提高效率
     */
    @Test
    public void readFile02() {
        String filePath = "E:\\hello.txt";
        //字节数组
        byte[] buf = new byte[8];//一次读8个字节
        int readLen = 0;
        FileInputStream fileInputStream = null;
        try {
            //创建FileInputStream 对象,用于读取 文件
            fileInputStream = new FileInputStream(filePath);
            //从该输入流读取最多b.length字节的数据到字节数组。此方法将阻塞,直到某些输入可用。
            //如果返回-1,表示读取完毕
            //如果读取正常,返回实际读取的字节数
            while ((readLen = fileInputStream.read(buf)) != -1) {
                System.out.print(new String(buf, 0, readLen));//显示
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

FileOutputStream介绍

FileOutputStream应用实例1

要求:请使用FileOutputStream在a.txt文件中写入"hello,world",如果文件不存在,会创建文件(注意:前提是目录已经存在)

package com19.outputstream_;

import org.junit.jupiter.api.Test;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author 甲柒
 * @version 1.0
 * @title FileOutputStream01
 * @package com19.outputstream_
 * @time 2023/3/31 19:56
 */
public class FileOutputStream01 {
    public static void main(String[] args) {

    }

    /**
     * 演示使用FileOutputStream 将数据写到文件中,
     * 如果文件不存在,则创建该文件
     */
    @Test
    public void writeFile() {

        //创建FileOutputStream对象
        String filePath = "E:\\a.txt";
        FileOutputStream fileOutputStream = null;
        try {
            //得到FileOutputStream对象
            //说明
            //1. new FileOutputStream(filePath); 创建方式,当写入内容是,会覆盖原来的内容
            //2. new FileOutputStream(filePath, true); 创建方式,当写入内容是,会追加到文件后面
            fileOutputStream = new FileOutputStream(filePath, true);
            //写入一个字节
//            fileOutputStream.write('H');//
            //写入字符串
            String str = "hello,world!";
            //str.getBytes() 可以把 字符串 -> 字节数组
//            fileOutputStream.write(str.getBytes());
            /*
            public void write(byte[] b,
                  int off,
                  int len)
           throws IOException
           //将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流。
           */
            fileOutputStream.write(str.getBytes(), 0, 4);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

FileOutputStream应用实例2

要求:编程完成图片/音乐的拷贝

package com19.outputstream_;

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

/**
 * @author 甲柒
 * @version 1.0
 * @title FileCopy
 * @package com19.outputstream_
 * @time 2023/3/31 21:57
 */
public class FileCopy {
    public static void main(String[] args) {
        //完成 文件拷贝,将 E:\\钢铁侠0.jpg 拷贝 E:\\钢铁侠1.jpg
        //思路分析
        //1. 创建文件的输入流,将文件读取到程序
        //2. 创建文件的输出流,将读取到的文件数据,写入到指定的文件
        String srcFilePath = "E:\\钢铁侠0.jpg";
        String destFilePath = "E:\\钢铁侠1.jpg";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(srcFilePath);
            fileOutputStream = new FileOutputStream(destFilePath);
            //定义一个字节数组,提高读取效果
            byte[] buf = new byte[1024];
            int readLen = 0;
            while ((readLen = fileInputStream.read(buf)) != -1) {
                //读取到后,就写入到文件 通过 fileOutputStream
                //即 是一边读 一边写
                fileOutputStream.write(buf, 0, readLen);
            }
            System.out.println("拷贝成功~~~");

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                //关闭输入流和输出流释放资源
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

FileReader和FileWriter介绍

FileReader和FileWriter是字符流,即按照字符来操作IO

FileReader相关方法:

  1. new FileReader(File/String)
  2. read; //每次读取单个字符,返回该字符,如果到文件末尾返回-1
  3. read(char[]); //批量读取多个字符到数组,返回读取到的字符数,如果到文件末尾返回-1

相关API:

  1. new String(char[]); //将char[]抓换成String
  2. new String(char[], off, len); //将char[]的指定部分转换成String

FileWriter常用方法

  1. new FileWriter(File/String); //覆盖模式,相当于流的指针在首段
  2. new FileWriter(File/String, true); //追加模式,相当于流的指针在尾端
  3. write(int); //写入单个字符
  4. write(char[]); //写入指定数组
  5. write(char[], off, len); //写入指定数组的指定部分
  6. write(string); //写入整个字符串
  7. write(string, off, len); //写入字符串的指定部分

相关API:String类:toCharArray:将String转换成char[]

注意:
FileWriter使用后,必须要关闭(close)或刷新(flush),否则写入不到指定的文件

FileReader和FileWriter应用案例 

要求:

1、使用FileReader从story.txt读取内容,并显示

package com19.reader_;

import org.junit.jupiter.api.Test;

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

/**
 * @author 甲柒
 * @version 1.0
 * @title FileReader_
 * @package com19.reader_
 * @time 2023/4/1 14:21
 */
public class FileReader_ {
    public static void main(String[] args) {
    }

    /**
     * 单个字符读取文件
     */
    @Test
    public void readFile01() {
        System.out.println("========readFile01=========");
        String filePath = "E:\\story.txt";
        FileReader fileReader = null;
        int data = 0;
        //1. 创建FileReader对象
        try {
            fileReader = new FileReader(filePath);
            //循环读取
            while ((data = fileReader.read()) != -1) {
                System.out.print((char) data);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * 字符数组读取文件
     */
    @Test
    public void readFile02() {
        System.out.println("========readFile02=========");
        String filePath = "E:\\story.txt";
        FileReader fileReader = null;

        int readLen = 0;
        char[] buff = new char[8];
        //1. 创建FileReader对象
        try {
            fileReader = new FileReader(filePath);
            //循环读取 使用read(buff) 返回的是实际读取到的字符数
            while ((readLen = fileReader.read(buff)) != -1) {
                System.out.print(new String(buff, 0, readLen));
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }


}

2、使用FileWriter将"风雨过后,定见彩虹"写入到note.txt文件中,注意细节

package com19.writer_;

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

/**
 * @author 甲柒
 * @version 1.0
 * @title FileWriter_
 * @package com19.writer_
 * @time 2023/4/1 14:41
 */
public class FileWriter_ {
    public static void main(String[] args) {
        String filePath = "E:\\note.txt";
        FileWriter fileWriter = null;
        char[] chars = {'a', 'b', 'c'};
        try {
            fileWriter = new FileWriter(filePath);
            //write(int); //写入单个字符
            fileWriter.write('Q');

            //write(char[]); //写入指定数组
            fileWriter.write(chars);
            //write(char[], off, len); //写入指定数组的指定部分
            fileWriter.write("甲柒".toCharArray(), 0, 1);
            //write(string); //写入整个字符串
            fileWriter.write(" hello,world!你好");
            fileWriter.write("风雨过后,定见彩虹");
            //write(string, off, len); //写入字符串的指定部分
            fileWriter.write("北京郑州", 0, 2);
            //在数据量大的情况下,可以用循环操作

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //对应FileWriter,一定要关闭流,或者flush才能真正的把数据写入到文件
            //看源码分析
            /*
                    private void writeBytes() throws IOException {
                        this.bb.flip();
                        int var1 = this.bb.limit();
                        int var2 = this.bb.position();

                        assert var2 <= var1;

                        int var3 = var2 <= var1 ? var1 - var2 : 0;
                        if (var3 > 0) {
                            if (this.ch != null) {
                                assert this.ch.write(this.bb) == var3 : var3;
                            } else {
                                this.out.write(this.bb.array(), this.bb.arrayOffset() + var2, var3);
                            }
                        }

                        this.bb.clear();
                    }
             */
            try {
//                fileWriter.flush();
                //关闭文件流 等价于 flush() + 关闭
                fileWriter.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("程序结束~~~~");
    }
}

猜你喜欢

转载自blog.csdn.net/qq_59621600/article/details/129868994