学习韩顺平老师java基础笔记4.7

学习目标:

java IO 流


学习内容:

提示:这里可以添加要学的内容

例如:

  1. 文件
  2. 常用的文件操作
  3. IO 流原理及流的分类
  4. FileInputStream 介绍
  5. 节点流和处理流

学习产出:

1. 文件

1.1 什么是文件

文件,对我们并不陌生,文件是保存数据的地方,比如大家经常使用的word文档,txt文件,excel文件…都是文件。它既可以保存一-张图片也可以保持视频,声音…

1.2 文件流

文件在程序中是以流的形式来操作的
在这里插入图片描述
图片取之韩顺平老师(自用)

2 常用的文件操作

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

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

案例:

public class FileCreate {
    public static void main(String[] args) {

    }
    //方式一 new File(String pathname)
    @Test
    public void create01(){
        String path ="D:\\JavaSe1\\File\\new01.txt";
        File file = new File(path);
        try {
            file.createNewFile();
            System.out.println("创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //方式 2 new File(File parent,String child) //根据父目录文件+子路径构建
    //e:\\news2.txt
    @Test
    public void create02(){
        File parentparh = new File("D:\\JavaSe1\\File\\");
        String chind ="new02.txt";
        File file = new File(parentparh, chind);
        try {
            file.createNewFile();
            System.out.println("创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

   //方式 3 new File(String parent,String child) //根据父目录+子路径构建
    @Test
    public void create03(){
        String parentpath ="D:\\JavaSe1\\File\\";
        String child="new03.txt";
        File file = new File(parentpath, child);
        try {
            file.createNewFile();
            System.out.println("创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2.2 获取文件的相关信息

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

2.3 应用案例演示

public class FileInfomation {
    public static void main(String[] args) {

    }
    //获取文件信息
    @Test
    public void info(){
        //先创建文件对象
        File file = new File("D:\\JavaSe1\\File\\new01.txt");
        //调用相应的方法,得到对应信息
        System.out.println("文件名字="+file.getName());
        System.out.println("文件的绝对路径"+file.getAbsolutePath());
        System.out.println("文件父级目录"+file.getParent());
        System.out.println("文件大小(字节)"+file.length());
        System.out.println("文件是否存在"+file.exists());
        System.out.println("是不是一个文件"+file.isFile());
        System.out.println("是不是一个目录"+file.isDirectory());
    }
}

2.4 目录的操作和文件删除

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

2.5 应用案例演示

public class Directory_ {
    public static void main(String[] args) {

    }
    //1.判断D:\JavaSe1\File\new01.txt 是否存在,如果存在就删除
    @Test
    public void m1(){
        File file = new File("D:\\JavaSe1\\File\\new01.txt");
        if (file.exists()){
            if(file.delete()){
                System.out.println(file+"文件删除成功");
            }else {
                System.out.println("删除失败");
            }
        }else {
            System.out.println("文件不存在");
        }
    }

    //2.判断 D:\\demo02 是否存在,存在就删除,否则提示不存在
    @Test
    public void m2(){
        File file = new File("D:\\demo02");
        if (file.exists()){
            if (file.delete()){
                System.out.println("删除成功");
            }else {
                System.out.println("删除失败");
            }
        }else {
            System.out.println(file+"文件不存在");
        }
    }

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

3. IO 流原理及流的分类

3.1 Java IO 流原理

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

3.2 流的分类

1.按操作数据单位不同分为:字节流(8 bit)二进制文件,字符流(按字符)文本文件
2.按数据流的流向不同分为:输入流,输出流
3.按流的角色的不同分为:节点流,处理流/包装流

在这里插入图片描述
图片取之韩顺平老师(自用)

4. IO 流体系图-常用的类

4.1 IO 流体系图
 IO 流体系图
图片取之韩顺平老师(自用)

文件 VS 流
在这里插入图片描述
图片取之韩顺平老师(自用)

4.2 FileInputStream 应用实例

public class FileInputStream_ {
    public static void main(String[] args) {

    }

    /**
     * 演示读取文件
     * 单个字节的读取,效率比较低
     * --->可以使用 read(byte [] b)
     */
    @Test
    public void readFile01() {
        //1.创建一个FileputStream对象
        FileInputStream fileInputStream = null;
        int readfile = 0;
        try {
            fileInputStream = new FileInputStream("D:\\JavaSe1\\File\\hello.txt");
            while ((readfile = fileInputStream.read()) != -1) {
                System.out.print((char) readfile);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 使用 read(byte [] b)来获取
     */
    @Test
    public void readFile02() {
        //1.创建一个FileputStream对象
        FileInputStream fileInputStream = null;
        byte[] buf = new byte[8];
        int readlength = 0;
        try {
            fileInputStream = new FileInputStream("D:\\JavaSe1\\File\\hello.txt");
            while ((readlength = fileInputStream.read(buf)) != -1) {
                System.out.print(new String(buf,0,readlength));//
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

4.3 FileOutputStream 介绍
在这里插入图片描述
图片取之韩顺平老师(自用)

4.4 FileOutputStream 应用实例

public class FileOutputStream_ {
    public static void main(String[] args) {

    }
    /**
     * 使用 FileOutputStream 将数据写到文件中,
     *  如果该文件不存在,则创建该文
     */
    @Test
    public void writeFile(){
        //先创建 FileOutputStream 对象
        FileOutputStream fileOutputStream =null;
        try {
            //1. new FileOutputStream(filePath) 创建方式,当写入内容是,会覆盖原来的内容
            //2. new FileOutputStream(filePath, true) 创建方式,当写入内容是,是追加到文件后面
          fileOutputStream = new FileOutputStream("D:\\JavaSe1\\File\\hello01.txt",true);
          //使用write方法写入一个字符
          //fileOutputStream.write('a');
          String str = "hello,wusong";
          //str.getBytes() 将字符串转成字节数组
          //fileOutputStream.write(str.getBytes());
         //   write(byte[] b, int off, int len) 将 len 字节从位于偏移量 off 的指定字节数组写入此文件输出流
          fileOutputStream.write(str.getBytes(),0,3);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4.5 文件拷贝 FileOutputStream 应用实例

public class FileCopy {
    public static void main(String[] args) {
        //完成文件拷贝
        //创建输入流和输出流
        FileInputStream fileInputStream =null;
        FileOutputStream fileOutputStream = null;
        byte[] bytes = new byte[1024];
        int bytelength =0;
        //读取文件
        try {
            fileInputStream =new FileInputStream("D:\\JavaSe1\\File\\bg.png");
            fileOutputStream =new FileOutputStream("D:\\JavaSe1\\copy\\bg.png");
            while ((bytelength=fileInputStream.read(bytes))!=-1){
                fileOutputStream.write(bytes,0,bytelength);
            }
            System.out.println("拷贝完成");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fileInputStream!=null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream!=null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

}

4.6 FileReader 和 FileWriter 介绍
在这里插入图片描述
图片取之韩顺平老师(自用)

4.7 FileReader 相关方法

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

相关API:

  1. new String(char[):将char[]转换成String
  2. newString(char[,off.Ien):将charD的指定部分转换成String

4.8 FileWriter 常用方法

  1. new FileWriter(File/String): 覆盖模式,相当于流的指针在首端
  2. new FileWriter(File/String,true): 追加模式,相当于流的指针在尾端
  3. write(int):写入单个字符
  4. write(char[]):写入指定数组
  5. write(char[,offlen):写入指定数组的指定部分
  6. write (string) :写入整个字符串
  7. write(string,off,len):写入字符串的指定部分
    相关API:
    String类: toCharArray:将String转换成char[]
    ➢注意
    FileWriter使用后,必须要关闭(close)或刷新(flush), 否则写入不到指定的文件!

4.9 FileReader 和 FileWriter 应用案例

要求: 1) 使用 FileReader 从 story.txt 读取内容,并显示

实现:

public class readerFile {
    public static void main(String[] args) {
        String path = "D:\\JavaSe1\\File\\hello01.txt";
        FileReader fileReader = null;
        char[] chars=new char[8];
        int charlength = 0;
        try {
            fileReader =new FileReader(path);
            while ((charlength=fileReader.read(chars))!=-1){
                System.out.println(new String(chars,0,charlength));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  1. 使用 FileWriter 将 “风雨之后,定见彩虹” 写入到 note.txt 文件中
public class FileWriter_ {
    public static void main(String[] args) {
        //1.创建一个FileWriter对象
        FileWriter fileWriter = null;
        char[] chars = {'a','b','c'};
        try {
            fileWriter = new FileWriter("D:\\JavaSe1\\File\\note.txt");
            //3) write(int):写入单个字符
            fileWriter.write('H');
            //4) write(char[]):写入指定数组
              fileWriter.write(chars);
            //5) write(char[],off,len):写入指定数组的指定部分
              fileWriter.write(chars,0,2);
            // 6) write(string):写入整个字符串
            fileWriter.write("你好北京");
            fileWriter.write("风雨之后,定见彩虹");
            //7) write(string,off,len):写入字符串的指定部分
            fileWriter.write("你好北京",0,2);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {//关闭流
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

5. 节点流和处理流

5.1 基本介绍
在这里插入图片描述
图片取之韩顺平老师(自用)

5.2 节点流和处理流一览图
在这里插入图片描述
5.3 节点流和处理流的区别和联系

1.节点流是底层流/低级流,直接跟数据源相接。
2.处理流(包装流)包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出。[源码理解]
3.处理流(也叫包装流)对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连[模拟修饰器设计模式=》小伙伴就会非常清楚]

5.4 处理流的功能主要体现在以下两个方面

1.性能的提高:主要以增加缓冲的方式来提高输入输出的效率。
2. 操作的便捷:处理流可能提供了-系列便捷的方法来一 次输入输出大批量的数据,使用更加灵活方便

5.5 处理流-BufferedReader 和 BufferedWriter
案例1:使用BufferedReader 读取文本文件,并显示在控制台

public class BufferedReader_ {
    public static void main(String[] args) {

        BufferedReader bufferedReader = null;
        String filepa = "D:\\JavaSe1\\File\\note.txt";
        //创建BufferedReader对象
        try {
            bufferedReader = new BufferedReader(new FileReader(filepa));
            //读取
            String line;//按行读取
            //1.bufferedReader.readLine() 按行读取文件
            //2.当返回一个null时,表示读取完毕
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流,这里注意,只需要关闭 bufferedReader,因为底层会自动去关闭 节点流
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

案例2:使用BufferedWriter 将"hello,韩顺平教育",写入文件中

public class BufferedWriter_ {
    public static void main(String[] args) throws IOException {
        //创建BufferWriter对象
        String filepath= "D:\\JavaSe1\\File\\ok.txt";
        //1.new FileWriter(filepath,true) 表示以追加的方式写入
        //2.new FileWriter(filepath) 表示以覆盖的方式写入
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filepath,true));
        bufferedWriter.write("hello,韩顺平教育");
        bufferedWriter.newLine();//插入一个和系统下相关的换行
        bufferedWriter.write("hello,韩顺平教育");
        bufferedWriter.newLine();//插入一个和系统下相关的换行
        bufferedWriter.write("hello,韩顺平教育");
        //插入一个换行符
        //关闭外层流即可,传入的new FileWriter会再底层关闭
        bufferedWriter.close();//
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值