【Java】IO流

概述

IO分类

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

抛异常要用try-catch-finally的方式

InputStream

InputStream的transferTo()方法可以把输入流中的所有数据自动地复制到输出流中
在这里插入图片描述

节点流(文件流)

字符流 FileReader 和FileWriter

字符流 处理的数据单位是char 针对文本文件
对于文本文件(.txt,.java,.c,.cpp),使用字符流处理

FileReader()

写入的步骤

  1. File类的实例化(如果文件不存在则会报错
  2. FileReader流的实例化
  3. 读入的操作
  4. 资源的关闭
  • read() 空参的方法 表示每次读入一个字符
    read() 返回读入的一个字符,如果达到文件末尾,返回-1
@Test
public void testFileReader()  {
    FileReader fr = null;
    try {
        //1. 实例化File类的对象,指明要操作的文件
        File file = new File("hello.txt");

        //2. 提供具体的流
        fr = new FileReader(file);

        //3. 数据的读入
        //read() 返回读入的一个字符,如果达到文件末尾,返回-1
        int data;
        while((data = fr.read())!=-1){
            System.out.print((char) data);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //4.流的关闭操作
        if (fr != null) {

            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}

  • read(char [] cbuf) 读入char型数组
    返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1

其他地方不变 数据读入的地方可以改成
方式一:

char[] cbuf = new char[5];
int len;
while((len=fr.read(cbuf))!=-1){
    for (int i = 0; i < len; i++) {
        System.out.print(cbuf[i]);
    }
}

方式二: 放到String中

 //3. 数据的读入
 char[] cbuf = new char[5];
 int len;//记录每次读入到cbuf数组中字符的个数
while((len=fr.read(cbuf))!=-1){
    String str = new String(cbuf,0,len);
    System.out.println(str);
}

FileWriter

从内存中写出数据到硬盘的文件里

写出的步骤

  1. 提供File类的对象,指明写出到的文件
    如果文件不存在,会自动创建一个
    如果文件存在,append参数为true则在原有文件追加,为false则覆盖,默认为false
  2. 提供FileWriter的对象,用于数据的写出
  3. 写出的操作
  4. 流资源的关闭
@Test
public void testFileWriter() throws IOException {
    //1. 提供File类的对象,指明写出到的文件
    File file = new File("hello1.txt");

    //2. 提供FileWriter的对象,用于数据的写出
    FileWriter fw = new FileWriter(file);

    //3. 写出的操作
    fw.write("i have a dream!".toCharArray());

    //4. 流资源的关闭
    fw.close();
}  

读入和写出一起示例

@Test
public void testFileReaderFileWriter() {
    //1. 创建File类的对象,指明读入和写出的文件
    FileReader fr = null;
    FileWriter fw = null;
    try {
        File srcFile = new File("hello.txt");
        File destFile = new File("hello2.txt");

        //2. 创建输入流和输出流的对象
        fr = new FileReader(srcFile);
        fw = new FileWriter(destFile);

        //3. 输入的读入和写出操作
        char[] cbuf = new char[5];
        int len;//记录每次读入到cbuf数组中字符重的个数
        while((len=fr.read(cbuf))!=-1){
            //每次写出len个字符
            fw.write(cbuf,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //4. 关闭流资源

        try {
            if(fw!=null)
                fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if(fr!=null)
                fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

字节流: FileInputStream FileOutputStream

字节流数据是字节,对于图片的写入和写出就要用字节流
对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt) 使用字节流处理
如果只是想对文本文件进行复制,那可以用字节流。相当于只是一个搬运工。

用 FileInputStream FileOutputStream实现对图片的复制

@Test
public void testFileInputStream(){
    FileInputStream fis = null;
    FileOutputStream fos  = null;
    try {
        File srcFile = new File("hhh.png");
        File destFile = new File("hhh1.png");

        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);

        byte[] buffer = new byte[5];
        int len;
        while((len = fis.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {

        try {
            if(fis!=null)
                fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if(fos!=null)
                fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

处理流

缓冲流(处理流的一种)

缓冲流的主要就是为了提高读取和写入文件的效率,开发中一般都用的缓冲流
能够提高速度的原因是内部提供了一个缓冲区

BufferedInputStream BufferedOutputStream

就是用缓冲流把原来的节点流包住
实现非文本文件的复制:

@Test
public void testFileInputStream(){
    //1. 造文件
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        File srcFile = new File("hhh.png");
        File destFile = new File("ddd.png");

        //2. 造流
        //2.1 造节点流
        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);
        //2.2 造缓冲流
        bis = new BufferedInputStream(fis);
        bos = new BufferedOutputStream(fos);

        //3. 复制的细节:读取、写入
        byte[] buffer = new byte[10];
        int len;
        while((len=bis.read(buffer))!=-1){
            bos.write(buffer,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        //4. 资源关闭
        //要求先关闭外层的流,再关闭内层的流。但关闭外层流的同时,内层流也会自动关闭。 所以可以省略
        if(bos!=null){
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (bis!=null){
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

BufferedReader BufferedWriter

BufferedReader BufferedWriter把FileReader和FileWriter包住,实现对文本文件的复制

@Test
public void testFileInputStream(){
    BufferedReader br = null;
    BufferedWriter bw = null;

    try {
        //1. 造文件 造流
        br = new BufferedReader(new FileReader(new File("hello.txt")));
        bw = new BufferedWriter(new FileWriter(new File("hhh7.txt")));

        //2. 读写操作
        char[] cbuf = new char[1024];
        int len;
        while((len = br.read(cbuf))!=-1){
            bw.write(cbuf,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //3.资源关闭
        if(br!=null){
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(bw!=null){
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}
  • 读写操作方式一:
    使用char[] 数组
        char[] cbuf = new char[1024];
        int len;
        while((len = br.read(cbuf))!=-1){
            bw.write(cbuf,0,len);
        }
   
  • 读写操作方式二:
String data;
while((data = br.readLine())!=null){
    //方法一:自己加换行符
    bw.write(data);
    bw.newLine();
}

转换流(处理流的一种)

  1. 转换流提供了字节流和字符流之间的转换
  2. 转换流属于字符流,因为后缀是Reader和Writer

InputStreamReader

InputStreamReader是将一个字节的输入流转换为字符的输入流;

isr = new InputStreamReader(fis,"UTF-8");
参数2指明了字符集,具体使用哪个字符集,取决于文件保存时使用的字符集

@Test
public void testFileInputStream()  {

    InputStreamReader isr = null;
    try {
        FileInputStream fis = new FileInputStream("hello.txt");
        //参数2指明了字符集,具体使用哪个字符集,取决于文件保存时使用的字符集
        isr = new InputStreamReader(fis,"UTF-8");

        char[] cbuf = new char[20];
        int len;
        while ((len=isr.read(cbuf))!=-1){
            String str = new String(cbuf, 0, len);
            System.out.println(str);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(isr!=null){
            try {
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

OutputStreamWriter

OutputStreamWriter是将一个字符的输出流转换为字节的输出流
在这里插入图片描述像上图一样把utf8.txt 转成gbk.txt

@Test
public void testFileInputStream()  {
    InputStreamReader isr = null;
    OutputStreamWriter osw = null;
    try {
        //造流
        FileInputStream fis = new FileInputStream("hello.txt");
        FileOutputStream fos = new FileOutputStream("gbk.txt");

        isr = new InputStreamReader(fis,"utf-8");
        osw = new OutputStreamWriter(fos,"gbk");

        //读写过程
        char[] cbuf = new char[20];
        int len;
        while((len=isr.read(cbuf))!=-1){
            osw.write(cbuf,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(isr!=null){
            try {
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(osw!=null){
            try {
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}

字符集

在这里插入图片描述

对象流

  1. 用于存储和读取基本数据类型数据或对象的处理流。对象流的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。

对象序列化机制

  1. 对象序列化机制
  • 序列化:对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。
  • 反序列化:当其它程序获取了这种二进制流,就可以恢复成原来的Java对象
  1. ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员。所以如果有一个属性不想被序列化,就可以加上transient。

对象可序列话要求

  1. 如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可序列化的
  • 该类必须实现如下两个接口之一:Serializable和、Externalizable
  • 还要显示提供一个serialVersionUID
    public static final long serialVersionUID = -28238373737L;
  • 除了当前类需要实现Serializable接口之外,还必须保证内部所有属性也必须是可序列化的(默认情况下,基本数据类型都是可序列化的)

序列化 ObjectOutputStream

序列化:用ObjectOutputStream类保存基本数据类型数据或对象的机制(写数据

public void test()  {
    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
        oos.writeObject(new String("我爱北京天安门"));
        oos.flush();//刷新操作
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(oos!=null){
            try {
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

反序列化 ObjectInputStream

反序列化:用ObjectInputStream类读取基本类型数据或对象的机制

public void test2() {
    ObjectInputStream ois = null;
    try {
        ois = new ObjectInputStream(new FileInputStream("object.dat"));
        Object obj = ois.readObject();
        String str = (String)obj;
        System.out.println(str);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        if(ois!=null){
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

随机存取文件流 RandomAccessFile

  1. RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
  2. RandomAccessFile既可以作为一个输入流,又可以作为一个输出流
  3. mode
  • r 以只读方式打开
  • rw打开以便读取和写入
  • rwd打开以便读取和写入;同步文件内容的更新
  • rws打开以便读取和写入;同步文件内容和元数据的更新

示例一:实现图片的复制

public void test()  {
    RandomAccessFile raf1 =null;
    RandomAccessFile raf2 =null;
    try {
        raf1 = new RandomAccessFile(new File("ddd.png"),"r");
        raf2 = new RandomAccessFile(new File("ddd1.png"),"rw");
        byte[] buffer = new byte[1024];
        int len;
        while ((len=raf1.read(buffer))!=-1){
            raf2.write(buffer,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(raf1!=null){
            try {
                raf1.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(raf2!=null){
            try {
                raf2.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
  1. 如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建;如果写出到的文件存在,则会对原有文件重新覆盖,默认是从头开始

示例二: 实现数据的插入效果
注意应该要用try-catch-finally

public void test2() throws IOException{
    RandomAccessFile raf = new RandomAccessFile("hello1.txt","rw");
    raf.seek(3);//将指针调到角标为3的位置
    //保存指针3后面的所有数据到StringBuilder中
    StringBuilder builder = new StringBuilder((int)new File("hello.txt").length());
    byte[] buffer = new byte[20];
    int len;
    while((len = raf.read(buffer))!=-1){
        builder.append(new String(buffer,0,len));
    }
    //调回指针,写入要插入的数据
    raf.seek(3);
    raf.write("aaaa".getBytes());

    //将StringBuilder中的数据写入到文件中
    //raf.write(builder.toString().getBytes());
    raf.close();
}

其他流(了解)

标准的输入、输出流

System.in标准的输入流,默认从键盘输入
System.out 标准的输出流,默认从控制台输出
在这里插入图片描述

练习:
从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,直至输入e或exit时,退出程序

使用System.in–>转换流–>BufferedReader的readLine()

public class FileReaderWriterTest {
    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            InputStreamReader isr = new InputStreamReader(in);
            br = new BufferedReader(isr);
            
            while(true){
                String data = br.readLine();
                if("e".equalsIgnoreCase(data)||"exit".equalsIgnoreCase(data)){
                    break;
                }
                String s = data.toUpperCase();
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }



    }
}

打印流

PrintStream 和PrintWriter 提供了一系列重载的print和println方法
在这里插入图片描述

数据流

  1. 为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流。
  2. 作用:用于 读取或写出基本数据类型的变量或字符串
    DataInputStream和

DataOutputStream

将内存中的字符串、基本数据类型的变量写出到文件中
这里保存的文件 不是让我们双击打开的,是要通过DataInputStream读取的

@Test
public void test() throws IOException {
    DataOutputStream dos = new DataOutputStream(new FileOutputStream("ii.txt"));

    dos.writeUTF("张小凡");
    dos.flush();//刷新。 将内存中的数据写入文件
    dos.writeInt(123);
    dos.flush();
    dos.writeBoolean(true);
    dos.flush();

    dos.close();
}

DataInputStream

将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。
注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致

@Test
public void test2() throws IOException {
    DataInputStream dis = new DataInputStream(new FileInputStream("ii.txt"));

    String name = dis.readUTF();
    int age = dis.readInt();
    boolean isMale = dis.readBoolean();

    System.out.println("name = "+name);
    System.out.println("age="+age);
    System.out.println("isMale="+isMale);

    dis.close();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值