IO流

发布时间 2023-03-23 22:36:51作者: 断剑重铸的锐萌萌

I/O流

分类

按照方向分:输入流,输出流

按照单位分:字节流,字符流

字节流:以字节为单位,可以读写所有数据

字符流:以字符为单位,只能读写文本数据

按照功能分:节点流,过滤流

文件字节输入流

演示FileInputStream的使用

package chapter3;

import java.io.FileInputStream;

public class Demo01 {
    //演示FileInputStream的使用
    //文件字节输入流
    public static void main(String[] args) throws Exception{
        //创建 FileInputStream,并且指定文件路径
        FileInputStream fis = new FileInputStream("e:\\aaa.txt");
        //读取文件
        //单个字节读取
//        int date=0;
//        while ((date=fis.read())!=-1){
//            System.out.println(date);
//        }
        //多个字节读取
        byte[] buff = new byte[3];
        int count=0;
        while ((count=fis.read(buff))!=-1){
            System.out.println(new String(buff,0,count));
        }
        //buff指的是读取数组的值,0指的是从0开始读,count指的是读到这个位置停止

        //关闭
        fis.close();
        System.out.println("执行完毕");
    }
}

文件字节输出流的使用

FileOutputStream方法
package chapter3;

import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;

public class Demo02 {
    //演示文件字节输出流的使用
    //FileOutputStream
    public static void main(String[] args) throws Exception{
        //创建文件字节输出流对象
        FileOutputStream fos = new FileOutputStream("e:\\bbb.txt");
        //FileOutputStream fos = new FileOutputStream("e:\\bbb.txt",true);
        //如果不想被覆盖,后面加一个true,将会每次把新的字符写到原来的后面
        //写入文件
        //单个写的太慢,调用getbyte方法
//        fos.write(97);
//        fos.write('b');
//        fos.write('c');
        String str="Hello World";
        fos.write(str.getBytes(StandardCharsets.UTF_8));
        //关闭
        fos.close();
        System.out.println("执行完毕");
    }
}

运用文件字节流实现复制

package chapter3;

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

public class Demo03 {
    //使用文件字节流实现文件的复制
    public static void main(String[] args) throws Exception{
        //创建流
        //创建文件字节输入流
        FileInputStream fis = new FileInputStream("e:\\001.jpg");
        //创建文件字节输出流
        FileOutputStream fos = new FileOutputStream("e:\\002.jpg");
        //一遍读一边写
        byte[] bytes = new byte[1024];
        int count=0;
        while ((count=fis.read(bytes))!=-1){
            fos.write(bytes,0,count);
        }
        //关闭
        fis.close();
        fos.close();
        System.out.println("复制完毕 ");
    }
}

字节缓冲流

缓冲流:创建一个缓冲区用来存储数据,增强底层流的输入输出效率

​ 提高IO效率,减少访问磁盘次数

​ 数据存储存储在缓冲区中,flush是将缓冲区的内容写入文件中,也可以直接close

package chapter3;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

public class Demo04 {
    //使用字节缓冲流读取
    //BufferedInputStream
    public static void main(String[] args) throws Exception{
        //创建BufferedInputStream
        //创建基本的字节输出刘,然后通过缓冲流来读取数据
        FileInputStream fis = new FileInputStream("e:\\aaa.txt");
        BufferedInputStream bis = new BufferedInputStream(fis);
        int date=0;
        //读取数据
        //先读取到bis缓冲区中,一次读取8k,然后再从缓冲区中一个字节一个字节的读取出来
//        while ((date=bis.read())!=-1){
//            System.out.print((char) date);
//        }
        //也可以自己创建一个长度的缓冲区来存放数据
        byte[] buff = new byte[1024];
        int count=0;
        while ((count=bis.read(buff))!=-1){
            System.out.println(new String(buff,0,count));
        }

        //关闭
        bis.close();
    }
}

使用BufferedinPutStream:通过设置这种输出流,应用程序就可以将各个字节写入底层输出流中,而不必针对每次字节写入调用底层系统。

package chapter3;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;

public class Demo05 {
    //使用字节缓冲流写入文件
    //BufferedOutputStream
    public static void main(String[] args) throws Exception{
        //创建字节输出缓冲流
        //BufferedOutputStream
        FileOutputStream fos = new FileOutputStream("e:\\buffer.txt");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        //写入文件
        for (int i = 0; i < 10; i++) {
            bos.write("Hello world\r\n".getBytes(StandardCharsets.UTF_8));//这里只是写到了bos缓冲区里面,还没有写到底层
            //所以要调用flush来刷新到硬盘
            bos.flush();
        }
        //关闭
        bos.close();
        System.out.println("完毕");
    }
}

序列化

学生类,注意:序列化和反序列化的时候,类要Serializable实现这个接口才可以被序列化

package chapter3;

import java.io.Serializable;

public class Student implements Serializable {//必须得实现这个接口,该类才可以别序列化,标记接口,仅仅使该类可以被序列化
    private String name;
    private int age;

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

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

    public Student() {
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

序列化

package chapter3;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class Demo06 {
    //ObjectOutputStream
    //要求:序列化的类型必须要实现Serializable接口
    public static void main(String[] args) throws Exception{
        //创建对象流
        FileOutputStream fos = new FileOutputStream("e:\\stu.bin");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        //序列化(写入操作
        Student zs = new Student("张三", 20);
        oos.writeObject(zs);
        //关闭
        oos.close();
        System.out.println("序列化完毕");
    }
}

反序列化

package chapter3;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class Demo07 {
    //使用ObjectInputStream实现反序列化(读取重构对象
    public static void main(String[] args) throws Exception{
        //创建对象流
        FileInputStream fis = new FileInputStream("e:\\stu.bin");
        ObjectInputStream ois = new ObjectInputStream(fis);
        //读取文件,(反序列化
        Student s=(Student) ois.readObject();
        //关闭
        ois.close();
        System.out.println(s);
    }
}

注意事项:

  1. 序列化类必须要实现Serializable接口
  2. 序列化类中对象属性要求实现Serializable接口
  3. 序列化版本号ID serialVersionUID,保证序列化的类和反序列化的类是同一个类
  4. 使用transient(瞬间的)修饰属性,这个属性不能被序列化
  5. 静态属性不能序列化
  6. 序列化多个对象,可以借助集合实现

字符流

package chapter3;

import java.io.FileReader;

public class Demo08 {
    public static void main(String[] args) throws Exception{
        //使用Fileread读取文件
        //创建fileread字符输入流
        FileReader fr = new FileReader("e:\\hello.txt");
        //读取
        //单个字符读取
//        int date=0;
//        while ((date=fr.read())!=-1){
//            System.out.print((char) date);
//        }
        //缓冲区读取
        char[] buf = new char[1024];
        int count=0;
        while ((count=fr.read(buf))!=-1){
            System.out.println(new String(buf,0,count));
        }
        fr.close();
    }
}
package chapter3;

import java.io.FileWriter;

public class Demo09 {
    //使用字符流写入文件
    public static void main(String[] args) throws Exception{
        //创建对象
        FileWriter fw = new FileWriter("e:\\write.txt");
        //写入
        for (int i = 0; i < 10; i++) {
            fw.write("java是世界上最好的语言\r\n");
            fw.flush();
        }
        fw.close();
        System.out.println("完毕");
    }
}

使用read和wirte复制文件只能复制文本文件,不能复制图片和二进制文件

package chapter3;

import java.io.FileReader;
import java.io.FileWriter;

public class Demo10 {
    //使用read和wirte复制文件
    //只能复制文本文件,不能复制图片和二进制文件
    public static void main(String[] args) throws Exception{
        //创建fileread和filewrite对象
        FileReader fr = new FileReader("e:\\write.txt");
        FileWriter fw = new FileWriter("e:\\write2.txt");
        //读写
        int date=0;
        while ((date=fr.read())!=-1){
            fw.write(date);
            fw.flush();
        }
        fr.close();
        fw.close();
        System.out.println("完毕");
    }
}

所以要是复制图片就得使用字节流辅助

字符缓冲流

高效读写,支持输入换行符,可一次写一行,读一行。

package chapter3;

import java.io.BufferedReader;
import java.io.FileReader;

public class Demo11 {
    //使用字符缓冲流来读取文件
    //BufferReader
    public static void main(String[] args) throws Exception{
        //创建缓冲流
        FileReader fr = new FileReader("e:\\write.txt");
        BufferedReader br = new BufferedReader(fr);
        //读取
        //第一种方式
//        char[] buf = new char[1024];
//        int date=0;
//        while ((date=br.read(buf))!=-1){
//            System.out.println(new String(buf,0,date));
//        }
        //第二种方式,一行一行的读
        String line=null;
        while ((line=br.readLine())!=null){
            System.out.println(line);
        }
        br.close();
    }
}
package chapter3;

import java.io.BufferedWriter;
import java.io.FileWriter;

public class Demo12 {
    public static void main(String[] args) throws Exception{
        //创建对象
        FileWriter fw = new FileWriter("e:\\hhh.txt");
        BufferedWriter bw = new BufferedWriter(fw);
        //写入数据
        for (int i = 0; i < 10; i++) {
            bw.write("java是世界上最好的语言哦");
            bw.newLine();//写入一个换行符\r\n
            bw.flush();
        }
        bw.close();
        System.out.println("完毕");
    }
}

打印流

package chapter3;

import java.io.PipedWriter;
import java.io.PrintWriter;

public class Demo13 {
    public static void main(String[] args) throws Exception{
        //创建打印流
        PrintWriter pw = new PrintWriter("d:\\print.txt");
        //打印
        pw.println(97);
        pw.println(true);
        pw.println(3.14);
        pw.println('a');
        pw.close();
        System.out.println("执行完毕");
    }

}

转换流

可以将字节流转换为字符流

可以设置字符的编码方式

File类

文件操作有:创建文件,删除文件,查询文件路径和父目录,文件长度,创建时间

以及判断文件是否可读,是否隐藏

package chapter3;

import java.io.File;
import java.util.Date;

public class Demo14 {
    //File类的使用
    //1.分隔符
    //2.文件操作
    //3.文件夹操作
    public static void main(String[] args) throws Exception{
        //separator();
        //fileOpe();
        directoryOpe();
    }
    public static void separator(){
        System.out.println("路径分隔符"+File.pathSeparator);
        System.out.println("名称分隔符"+File.separator);
    }
    public static void fileOpe() throws  Exception {
        //创建文件createNewFile(
        File file = new File("e:\\file.txt");
        if (!file.exists()){
            boolean b = file.createNewFile();
            System.out.println("创建结果"+b);
        }
        //删除文件
        //直接删除
        //System.out.println(file.delete());
        //使用jvm退出时删除
//        file.deleteOnExit();
//        Thread.sleep(5000);
        //获取文件信息
        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("是否可写"+file.canWrite());
        System.out.println("是不是文件"+file.isFile());
        System.out.println("是否隐藏"+file.isHidden());
    }
    public static void directoryOpe() throws Exception{
        //创建文件夹
        File file = new File("e:\\aaa\\bbb\\ccc");
        if (!file.exists()){
           // file.mkdir();//只能创建单级目录
            System.out.println("创建结果"+file.mkdirs());//可以创建多级目录
        }
        //删除文件夹
        //1.直接删除:只会删除最底层的那个目录文件,并且这个文件需要是空文件
        //file.delete();
        //2.使用jvm进行删除
//        file.deleteOnExit();
//        Thread.sleep(5000);

        //获取文件夹信息
        System.out.println("获取绝对路径"+file.getAbsolutePath());
        System.out.println("获取路径"+file.getPath());
        System.out.println("获取文件夹名称"+file.getName());
        System.out.println("获取父目录"+file.getParent());
        System.out.println("获取创建时间"+new Date(file.lastModified()));
        //判断
        System.out.println("是否是文件夹"+file.isDirectory());
        System.out.println("是否是隐藏"+file.isHidden());
        //遍历文件夹
        File file1 = new File("e:\\图片");
        String[] list = file1.list();
        for (String string:list){
            System.out.println(string);
        }
    }
}

Properties集合的使用

package chapter3;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.Set;

public class Demo15 {
    //Properties集合的使用
    public static void main(String[] args) throws Exception {
        //创建集合
        Properties properties = new Properties();
        //添加数据
        properties.setProperty("username","zhangsa");
        properties.setProperty("age","20");
        //遍历
        Set<String> set = properties.stringPropertyNames();
        for (String pro:set
             ) {
            System.out.println(pro+"   "+properties.getProperty(pro));
            
        }
        //和流有关的方法
        //list方法
//        PrintWriter pw = new PrintWriter("e:\\printhhh.txtx");
//        properties.list(pw);
//        pw.close();
        //store方法(保存
//        FileOutputStream fos = new FileOutputStream("e:\\store.properties");
//        properties.store(fos,"注释");
//        fos.close();

        //load方法(加载
        Properties properties1 = new Properties();
        FileInputStream fis = new FileInputStream("e:\\store.properties");
        properties1.load(fis);
        fis.close();
        System.out.println(properties1);
    }
}