【Java-15】IO流

package guo.java;

import org.junit.Test;

import java.io.*;

/**
 * 一、流的分类
 * 1.操作数据单位:字节流,字符流
 * 2.数据的流向:输入流,输出流
 * 3.流的角色:节点流,处理流
 *
 * 二、流的体系结构:
 * 抽象基类:            节点流(文件流)                缓冲流(处理流的一种)
 * InputStream          FileInputStream                 BufferedInputString
 * OutputStream         FileOutputStream                BufferedOutputString
 * Reader               FileReader                      BufferedReader
 * Writer               FileWriter                      BufferedWriter
 * @author Baobao
 * @create 2021-08-26  17:11
 */
public class FileReaderWriterTest {
    /*
    异常的处理:为了保证流资源一定可以执行关闭操作,需要使用try catch finally去处理
    读入的文件一定要存在,否则就会报出FileNotFoundException
     */
    @Test
    public void testFileReader() {
        FileReader f2= null;
        try {
            File file=new File("hello.txt");
            f2 = new FileReader(file);
            //read();方法:返回读入的一个字符,如果达到了文件末尾,就返回-1
            int data=f2.read();
            while(data!=-1){
                System.out.println((char)data);
                data=f2.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            //流的关闭操作
            try {
                if(f2!=null){
                    f2.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
    对read方法的操作升级:使用重载方法
     */
    @Test
    public void testFileReader1() throws IOException {
        //1.有对应的文件
        File file = new File("hello.txt");
        //2.流的实例化
        FileReader fr = new FileReader(file);
        //3.读入的具体的操作细节
        //返回每次读入数组中的字符的个数,如达到文件末尾,返回-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]);
            }
        }
        //4.资源的关闭
    }
    /*
    输出操作对应的file可以不存在,会自动创建新文件
    如果存在,会覆盖原有文件(后面写false)
    如果写true,就表示append追加
     */
    @Test
    public void testFileWriter() throws IOException {
        //1.提供file类的对象,指明写出到的文件
        File file = new File("hello1.txt");
        //2.提供FileWriter,用于数据写出
        FileWriter fw=new FileWriter(file,true);
        //3.写出的操作
        fw.write("I have a dream!");
        fw.write("You need to have a dream");
        //4.流的关闭
        fw.close();
    }

    //不能使用字符流来处理图片类的字节文件
    @Test
    public void testFileReaderFileWriter()  {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            //1.创建File类的对象,实现文件的复制
            File file = new File("hello.txt");
            File dest = new File("hello2.txt");
            //2.创建流对象
            fr = new FileReader(file);
            fw = new FileWriter(dest);
            //3.数据的读入写出
            char [] cbuf=new char[5];
            int len;
            while((len=fr.read(cbuf))!=-1){
                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();
            }
        }
    }
}
package guo.java;

import org.junit.Test;

import java.io.*;

/**
 * 对于文本文件,使用字符流来处理
 * 对于非文本文件,使用字节流来处理
 * @author Baobao
 * @create 2021-08-26  22:58
 */
public class FileInputOutputStreamTest {
    @Test
    public void testFileInputStream() throws IOException {
        File file=new File("hello.txt");
        FileInputStream fis= new FileInputStream(file);
        byte[] by=new byte[5];
        int len;
        while((len=fis.read(by))!=-1){

        }
        fis.close();
    }

    /*
    实现对文件的复制操作
     */
    @Test
    public void fileInputOutputStream() {
        FileInputStream fis= null;
        FileOutputStream fos= null;
        try {
            File srcfile=new File("hh.jpg");
            File destfile=new File("hh1.jpg");
            fis = new FileInputStream(srcfile);
            fos = new FileOutputStream(destfile);
            byte[] by=new byte[5];
            int len;
            while ((len=fis.read(by))!=-1){
                fos.write(by, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public void copyFile(String srcPath,String destPath){
        FileInputStream fis= null;
        FileOutputStream fos= null;
        try {
            File srcfile=new File(srcPath);
            File destfile=new File(destPath);
            fis = new FileInputStream(srcfile);
            fos = new FileOutputStream(destfile);
            byte[] by=new byte[5];
            int len;
            while ((len=fis.read(by))!=-1){
                fos.write(by, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
package guo.java;

import org.junit.Test;

import java.io.*;

/**
 * * 处理流之二:转换流的使用
 *  * 1.转换流:属于字符流
 *  * InputStreamReader将字节的输入流转换为字符的输入流
 *  * OutputStreamWriter将字符的输出流转换为字节的输出流
 *  *
 *  * 2.作用:提供字符流字节流之间的转换
 *  *
 *  * 3.字节->字符串:解码
 *  *   字符->字节:编码
 *  *
 *  * 4.字符集
 *  *
 * @author Baobao
 * @create 2021-08-27  17:07
 */
public class InputStreamReaderTest {
    @Test
    public void test01() throws IOException {
        FileInputStream fis = new FileInputStream("dbcp.txt");
        //参数2指明了字符集,具体使用哪个字符集取决于目标文件保存的时候使用的字符集
        InputStreamReader 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);
        }
        isr.close();
    }
    /*
    综合使用
     */
    @Test
    public void test2() throws IOException {
        File file1=new File("dbcp.txt");
        File file2=new File("dbcp_gbk.txt");

        FileInputStream fis=new FileInputStream(file1);
        FileOutputStream fos=new FileOutputStream(file2);
        //使用转换流去包入流:
        InputStreamReader isr=new InputStreamReader(fis,"utf-8");
        OutputStreamWriter osr=new OutputStreamWriter(fos,"gbk");

        char[] cbuf=new char[20];
        int len;
        while((len=isr.read(cbuf))!=-1){
            osr.write(cbuf, 0, len);
        }

        isr.close();
        osr.close();
    }
}
package guo.java;

import org.junit.Test;

import java.io.*;

/**
 * 处理流就是套结在已有的流之上的流
 * @author Baobao
 * @create 2021-08-27  12:19
 */
public class BufferedTest {
    //实现文件复制的方法
    public void copyFileWithBuffered(String srcPath,String destPath) {
        BufferedInputStream bis= null;
        BufferedOutputStream bos= null;
        try {
            bis = null;
            bos = null;
            File srcfile=new File(srcPath);
            File destfile=new File(destPath);
            FileInputStream fis=new FileInputStream(srcfile);
            FileOutputStream fos=new FileOutputStream(destfile);
            byte[] buffer=new byte[5];
            int len;
            while((len=bis.read(buffer))!=-1){
                bos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //可以省略关闭内层,会自动关闭。
            try {
                if(bis!=null)
                    bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(bos!=null)
                    bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /*
    使用BufferedReader BufferedWriter实现文本文件的复制
     */
    @Test
    public void testBufferedReaderWriter(){
        BufferedReader br= null;
        BufferedWriter bw= null;
        try {
            br = new BufferedReader(new FileReader(new File("dbcp.txt")));
            bw = new BufferedWriter(new FileWriter(new File("jdbc.txt")));

            char[] ch=new char[5];
            int len;
            while ((len=br.read(ch))!=-1){
                bw.write(ch, 0, len);
                bw.flush();//清空缓存区
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            try {
                if(br!=null)
                    br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(bw!=null)
                    bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
package guo.java;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Locale;

/**
 * 其他流的使用
 * 1.标准的输入输出流
 * 2.打印流
 * 3.数据流
 * @author Baobao
 * @create 2021-08-27  18:01
 */
public class OtherStreamTest {
    /*
    标准的输入输出流
    System类的setIn()和setOut()方式重新指定输入输出流。
    System.in->BufferedReader的ReadLine()
     */
    @Test
    public void test01(){
        BufferedReader br= null;
        try {
            //system是字节输入流,要转换为字符输入流才可以被bufferedReader包装
            InputStreamReader isr=new InputStreamReader(System.in);
            br = new BufferedReader(isr);
            while(true){
                String data=br.readLine();
                if(("e").equalsIgnoreCase(data)||("exit").equalsIgnoreCase(data)){
                    break;
                }
                String upper=data.toUpperCase(Locale.ROOT);
                System.out.println(upper);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
    打印流:PrintStream PrintWriter

    提供了一系列重载的print和println方法
     */
    @Test
    public void test2(){

    }
}
package java1;

import org.junit.Test;

import java.io.*;

/**
 * 对象流的使用
 * 1.ObjectInputStream
 *
 * 2.ObjectOutputStream
 *
 * 3.要想一个java对象是可序列化的
 * @author Baobao
 * @create 2021-08-30  16:12
 */
public class ObjectInputOutputStreamTest {
    /*
    序列化过程:将内存中的java对象保存到磁盘中,或者通过网络传输出去
    使用ObjectOutputStream
     */
    @Test
    public void testObjectOutputStream(){
        ObjectOutputStream oos= null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("object.txt"));
            oos.writeObject(new String("我爱北京天安门"));
            oos.flush();

            oos.writeObject(new Person("Tom", 20));
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(oos!=null){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /*
    反序列化:将磁盘文件中的对象还原为内存中的java对象
     */
    @Test
    public void testObjectInputStream(){
        ObjectInputStream ois= null;
        try {
            ois = new ObjectInputStream(new FileInputStream(new File("object.txt")));
            Object obj = ois.readObject();
            String str=(String) obj;
           Person p=(Person) ois.readObject();
            System.out.println(str);
            System.out.println(p);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(ois!=null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
package java1;

import org.junit.Test;

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

/**
 * RandomAccessFile的使用:
 * 1.直接继承与java.lang.object,实现了DataInput,DataOutput接口
 * 2.既可以作为输入流,也可以作为输出流
 * 3.输出的时候如果RandomAccessFile作为输出流,文件不存在,则在执行过程中自动创建;如果写出到的文件存在,
 *   则会对原有文件内容进行覆盖,默认情况下从头覆盖
 * 4.可以通过RandomAccessFile实现数据的插入
 * @author Baobao
 * @create 2021-08-30  17:07
 */
public class RandomAccessFileTest {
    @Test
    public void test1(){
        RandomAccessFile raf1= null;
        RandomAccessFile raf2= null;
        try {
            raf1 = new RandomAccessFile(new File("kkk.jpg"), "r");
            raf2 = new RandomAccessFile("kkk1.jpg", "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 (IOException e) {
                    e.printStackTrace();
                }
            }
            if(raf2!=null){
                try {
                    raf2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /*
    对内容的覆盖
     */
    @Test
    public void test2() throws IOException {
        RandomAccessFile raf1=new RandomAccessFile(new File("hello.txt"), "rw");
        raf1.seek(3);//指针移动
        raf1.write("xyz".getBytes());
        raf1.close();
    }
    /*
    使用RandomAccessFile实现文件的插入效果
     */
    @Test
    public void test03() throws IOException {
        RandomAccessFile raf1=new RandomAccessFile(new File("hello.txt"), "rw");
        raf1.seek(3);
        byte[] buffer=new byte[20];
        int len;
        //保存指针3之后的所有数据
        StringBuilder builder=new StringBuilder((int) new File("hello.txt").length());
        while((len=raf1.read(buffer))!=-1){
            builder.append(new String(buffer,0,len));
        }
        raf1.seek(3);
        raf1.write("xyz".getBytes());
        raf1.write(builder.toString().getBytes());
        raf1.close();
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值