Java基础 IO流

1、文件

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

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

以下三种方式进行创建文件 在e盘下分别创建文件

//方式一 根据路径构建一个File文件 new File(String pathname)
    @Test
    public void create01(){
        String pathCreate = "e:\\news1.txt";
        File file = new File(pathCreate);
        try {
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

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

2、常用的文件操作 

获取文件信息的常用方法:

getNamegetAbsolutePathgetParentlengthexistsisFileisDirectory

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

        System.out.println("文件名称"+file.getName());
        System.out.println("文件绝对路径"+file.getAbsoluteFile());
        System.out.println("文件的父级目录"+file.getParent());
        System.out.println("文件的大小(字节)"+file.length());
        System.out.println("文件是否存在"+file.exists());//T
        System.out.println("是不是一个文件"+file.isFile());//T
        System.out.println("是不是一个目录"+file.isDirectory());
    }

常用的文件操作: 

package com.wangbx.file;

import java.io.File;
import org.junit.jupiter.api.Test;

/**
 * @author WANGBX
 * @version 1.0
 */
public class Directory_ {

    //判断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("文件删除成功");
            }else {
                System.out.println("文件删除失败");
            }
        }else {
            System.out.println("文件不存在");
        }
    }

    //判断 d:\\demo2 是否存在,存在就删除,否则提示不存在
    //在这里可以体会到 在java编程中,目录也被当做文件
    @Test
    public void m2(){
        String filePath = "e:\\demo2";
        File file = new File(filePath);
        if(file.exists()){
            if(file.delete()){
                System.out.println("文件删除成功");
            }else {
                System.out.println("文件删除失败");
            }
        }else {
            System.out.println("该目录不存在");
        }
    }

    //判断 e:\\demo\\a\\b\\c目录是否存在 如果存在就提示存在 不存在则创建目录
    @Test
    public void m3(){
        String filePath = "e:\\demo\\a\\b\\c";
        File file = new File(filePath);
        if(file.exists()){
            System.out.println("该目录已存在");
        }else {
            if(file.mkdirs()){//一级目录使用mkdir 多级目录使用mkdirs
                System.out.println("文件目录创建成功");
            }else {
                System.out.println("文件目录创建失败");
            }
        }
    }
}

3、IO流的原理及流的分类

原理:

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

 文件的拷贝 此处是照片

    @Test
    public void copy(){
        //文件拷贝
        String scrPath = "e:\\wangbx.jpg";
        String destPath = "e:\\wang.jpg";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        byte[] bytes = new byte[1024];
        int readLen = 0;
        try {
            fileInputStream = new FileInputStream(scrPath);
            fileOutputStream = new FileOutputStream(destPath);
            while ((readLen = fileInputStream.read(bytes))!=-1){
                //边读边写
                fileOutputStream.write(bytes,0,readLen);//一定要使用这个方法
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fileInputStream != null){
                    fileInputStream.close();
                }
                if(fileOutputStream != null){
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
FileReader FileWriter 应用案例
//使用 FileReader 从 story.txt 读取内容,并显示
    //使用 FileReader 从 story.txt 读取内容,并显示 按照单个字符读取
    @Test
    public void reader(){
        String filePath = "e:\\story.txt";
        FileReader fileReader = null;
        int readLen = 0;

        try {
            fileReader = new FileReader(filePath);
            while ((readLen = fileReader.read()) != -1){
                System.out.print((char) readLen);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fileReader != null){
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //使用 FileReader 从 story.txt 读取内容,并显示 按照字符数组读取
    @Test
    public void readers(){
        String filePath = "e:\\story.txt";
        FileReader fileReader = null;
        int readLen = 0;
        char[] chars = new char[8];
        try {
            fileReader = new FileReader(filePath);
            while ((readLen = fileReader.read(chars)) != -1){
                System.out.print(new String(chars,0,readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fileReader != null){
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
使用 FileWriter 将 “风雨之后,定见彩虹” 写入到 note.txt 文件中 , 注意细节:
使用完毕之后一定要 close或flush
    //使用 FileWriter 将 “风雨之后,定见彩虹” 写入到 note.txt 文件中, 注意细节
    @Test
    public void writer01(){
        String filePath = "e:\\note.txt";
        FileWriter fileWriter = null;
        char[] chars = {'w','b','x'};
        try {
            fileWriter = new FileWriter(filePath);//此处默认是覆盖模式,如果想追加写入则需要在后面加true
            //写入单个字符
            fileWriter.write('w');
            //写入指定数组
            fileWriter.write(chars);
            //写入数组指定
            fileWriter.write("鲁迅原名周树人".toCharArray(),4,3);
            //写入整个字符串
            fileWriter.write("风雨之后,定见彩虹");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fileWriter != null){
                try {
                    //使用完FileWriter之后一定要关闭资源 或者flush 不然数据会写不进去
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

3、 节点流和处理流:

Java I/O(输入/输出)操作可以通过节点流和处理流来进行。

  1. 节点流(Node Stream):也称为低级流(Low-Level Stream),是直接与数据源或目的地连接的流。它们提供了最基本的读取和写入功能,例如从文件、网络、标准输入/输出等读取或写入字节或字符。

常见的节点流包括:

  • FileInputStream:用于从文件读取字节数据。
  • FileOutputStream:用于向文件写入字节数据。
  • FileReader:用于从文件读取字符数据。
  • FileWriter:用于向文件写入字符数据。
  • SocketInputStream 和 SocketOutputStream:用于通过网络读取和写入字节数据。
  1. 处理流(Filter Stream):也称为高级流(High-Level Stream),是对节点流进行封装,提供了更高级别的功能,例如缓冲、数据转换、序列化等。处理流通过包装节点流来增强其功能,并且可以嵌套使用。

常见的处理流包括:

  • BufferedInputStream 和 BufferedOutputStream:提供了缓冲读取和写入功能,可以提高 I/O 性能。
  • BufferedReader 和 BufferedWriter:提供了缓冲读取和写入字符数据的功能。
  • InputStreamReader 和 OutputStreamWriter:用于将字节流和字符流进行转换。
  • ObjectInputStream 和 ObjectOutputStream:用于对象的序列化和反序列化。
  • DataInputStream 和 DataOutputStream:用于读取和写入基本数据类型的数据。
  • PrintStream 和 PrintWriter:提供了格式化输出的功能。
  • GZIPInputStream 和 GZIPOutputStream:用于对数据进行压缩和解压缩。

使用处理流可以提供更方便和高效的 I/O 操作,尤其是在处理大量数据或需要复杂数据转换的情况下。节点流和处理流可以根据具体需求进行组合和嵌套使用,以满足不同的 I/O 操作需求。

    //使用BufferedReader读取文本文件 ,并显示在控制台
    @Test
    public void bufferedRead() throws IOException {
        String filePath = "e:\\a.java";

        //创建bufferedReader
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
        //按行读取
        String line;
        while ((line = bufferedReader.readLine())!= null){
            System.out.println(line);
        }

        //关闭流 此处只需关闭处理流 底层做了关闭节点流的方法
        bufferedReader.close();
    }
    //使用BufferedWriter写入
    @Test
    public void bufferedW() throws IOException {
        String filePath = "e:\\ok.txt";

        //FileWriter(filePath, true) 是以追加的方式进行添加数据
        BufferedWriter bufferedWriter =
                new BufferedWriter(new FileWriter(filePath, true));

        bufferedWriter.write("鲁迅原名周树人");
        //以系统的方式添加换行
        bufferedWriter.newLine();
        bufferedWriter.write("浙江绍兴人");
        bufferedWriter.newLine();


        bufferedWriter.close();
    }
    //使用BufferedReader 和 BufferedWriter 实现文档文件的拷贝
    //是按照字符操作的,不要去操作二进制文件 可能会造成损坏
    @Test
    public void copy() throws IOException {
        String scrFilePath = "e:\\a.java";
        String destFilePath = "e:\\a1.java";

        BufferedReader bufferedReader =
                new BufferedReader(new FileReader(scrFilePath));
        BufferedWriter bufferedWriter =
                new BufferedWriter(new FileWriter(destFilePath));

        String line;
        while ((line = bufferedReader.readLine())!= null){
            bufferedWriter.write(line);
            //每写一行添加跟系统相关的换行
            bufferedWriter.newLine();
        }
        //关闭流
        bufferedWriter.close();
        bufferedReader.close();
    }
    //将图片或视频拷贝 使用Buffered
    @Test
    public void copy() throws IOException {
        String srcFilePath = "e:\\wangbx.jpg";
        String destFilePath = "e:\\bx.jpg";

        BufferedInputStream br = new BufferedInputStream(
                new FileInputStream(srcFilePath));

        BufferedOutputStream bw = new BufferedOutputStream(
                new FileOutputStream(destFilePath));

        byte[] bytes = new byte[1024];
        int readLen = 0;
        while ((readLen = br.read(bytes))!=-1){
            bw.write(bytes,0,readLen);
        }
        System.out.println("完成拷贝~");

        br.close();
        bw.close();
    }
对象流 -ObjectInputStream ObjectOutputStream
功能:提供了对基本类型或对象类型的序列化和反序列化的方法
ObjectOutputStream 提供 序列化功能
ObjectInputStream 提供 反序列化功能
//先创建实现序列化接口的dog类
public class Dog implements Serializable {
        String name;
        Integer age;

        public Dog(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

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

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
//ObjectOutputStream 的使用, 完成数据的序列化
    public static void main(String[] args) throws IOException {
        //序列化后保存的是文件格式 而不是文本,而是按照他的格式来保存的
        String filePath = "e:\\data.dat";

        ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(filePath));

        //序列化数据到e:\data.dat
        oos.writeInt(100);//int -> Integer (实现了 Serializable)
        oos.writeBoolean(true);//boolean->Boolean(实现了Serializable)
        oos.writeChar('w');//char -> Char(实现了Serializable)
        oos.writeDouble(99.9);
        oos.writeUTF("周树人");

        //保存一个dog
        Dog dog = new Dog("旺财", 8);
        oos.writeObject(dog);

        oos.close();
        System.out.println("数据保存完毕····");
    }
    //反序列化读取文件
    public static void main(String[] args) throws IOException,
            ClassNotFoundException {
        //指定反序列化的文件
        String filePath = "e:\\data.dat";

        ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream(filePath));

        //读取,注意按照顺序读取
        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readChar());
        System.out.println(ois.readDouble());
        System.out.println(ois.readUTF());
        //dog的编译类型是 Object,dog的运行类型是Dog
        Object dog = ois.readObject();
        System.out.println("运行类型=" + dog.getClass());
        System.out.println("dog信息=" + dog);

        //关闭流
        ois.close();
    }
标准输入输出流
类型默认设备
System.in 标准输入InputStream键盘
System.out 标准输出PrintStream显示器

转换流-InputStreamReader OutputStreamWriter 

    //使用 InputStreamReader 转换流解决中文乱码问题
    //将字节流 FileInputStream 转成字符流 InputStreamReader, 指定编码 gbk/utf-8
    public static void main(String[] args)
            throws IOException {
        String filePath = "e:\\ok.txt";

        //根据转换流转换成字符流之后 再次进行处理流来增加效率
        BufferedReader br = new BufferedReader(
                new InputStreamReader(new FileInputStream(filePath), "gbk"));
        String s = br.readLine();
        System.out.println(s);
        //关闭外层流
        br.close();
    }
    //编程将字节流FileOutputStream包装成(转换成)字符流OutputStreamWriter,
    //对文件进行写入(按照gbk格式,可以指定其他,比如utf-8)
    public static void main(String[] args)
            throws IOException {
        String filePath = "e:\\转换流.txt";
        String charSet = "utf-8";
        OutputStreamWriter osw = new OutputStreamWriter(
                new FileOutputStream(filePath),charSet);
        osw.write("少年注不识愁滋味,爱上层楼,爱上层楼,为赋新词强说愁。\n"+
                "而今识尽注愁滋味,欲说还休注,欲说还休注,却道天凉好个秋!");
        osw.close();
        System.out.println("保存成功~");
    }
打印流 -PrintStream PrintWriter
    //PrintStream(字节打印流/输出流)
    public static void main(String[] args) throws IOException {

        PrintStream out = System.out;
        //默认情况下 PrintStream 输出数据的位置是 标准输出 即显示器
        out.print("hello,wangbx");

        //因为print底层使用的是writer,所以我们直接调用writer进行打印/输出
        out.write("周树人".getBytes());
        out.close();

        //我们可以去修改打印流输出的位置/设备
        //修改成 "e:\\f1.txt"
        System.setOut(new PrintStream("e:\\f1.txt"));
        System.out.println("hello~~~~~~~~~~~");
    }

 

    //PrintWriter
    public static void main(String[] args) throws IOException {
        //标准输出流 会输出到显示器
        //PrintWriter printWriter = new PrintWriter(System.out);
        //输出到文件
        PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f1.txt"));
        printWriter.println("你好");
        printWriter.close();
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值