Java高级知识复习----IO流

1.字符流输入流输出流,实现文本文件的复制

package top.oneluckyguy.thread;

import org.junit.Test;

import java.io.*;

/**
 * @author Liu Qingfeng
 * @create 2020-12-18----21:30
 */
public class FileReaderWritertest {
    public static void main(String[] args) {
        File file = new File("hello.txt");//相较于当前工程下
        System.out.println(file.getAbsolutePath());
    }
    /*
    将文件读入到程序中,并输出到控制台。

    知识点:
    1.read()的理解,返回读入的一个字符,如果到达文件末尾就返回-1
    2.异常的处理:为了保证流的资源一定关闭,最好使用try_catch_finally来捕获异常。

    * */

    @Test
    public void testFileReader() {
        FileReader fileReader = null;
        try {
            //        1.实例化File类的对象,并指明要操作的文件
            File file = new File("src//top//oneluckyguy//pro//hello.txt");//相较于当前Module下
//        2.提供具体的流
            fileReader = new FileReader(file);
//        3.数据的读入
            //read()返回读入的一个字符,如果达到文件末尾,返回-1
       /* 方式一
        int  data = fileReader.read();
        while(data != -1){
            System.out.println((char)(data));
            data = fileReader.read();
        }*/
            //方式二
            int data;
            while((data = fileReader.read()) != -1){
                System.out.println((char)data);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {

            //4.流的关闭
            if (fileReader != null){
                try {
                    fileReader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }

        }
    }
    @Test
    public void testFileReader1() throws IOException {
        FileReader fileReader = null;
        try {
            //1.File类的实例化
            File file = new File("src//top//oneluckyguy//pro//hello.txt");
            //2.FileReader流的实例化
            fileReader = new FileReader(file);
            //3.读入的操作
            //read(char[] cbuffer):返回每次读入cbuffer数组中的字符个数,如果达到文件末尾就返回-1
            char[] cbuffer = new char[5];
            int len;
            while ((len = fileReader.read(cbuffer)) != -1 ){
                //方式一
                // 如果是len.length输出为helloworld123ld,123会把world中的前三个字母覆盖,但是后三个不会覆盖,还是输出
                /*for (int i = 0; i < len; i++) {//这里是小于len不是小于len.length。
                    System.out.println(cbuffer[i]);
                }*/
                //方式二
                String string = new String(cbuffer,0,len);//如果这里不加0和len也会出现上面的错误
                System.out.println(string);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileReader != null){
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /*
    * 从内存中写出数据到硬盘的文件里
    * */
    @Test
    public void testFileWriter()  {
        FileWriter fileWriter = null;
        try {
//        1.提供File类的对象指明要写出的文件
            File file = new File("src//top//oneluckyguy//pro//hello1.txt");
//        2.提供FileWriter的对象,用于数据的写出
            fileWriter = new FileWriter(file,true);//加上true表示在原有文件上追加内容
//        3.写出操作
            fileWriter.write("I have a dream\n");
            fileWriter.write("You are beautiful");
//        4.流的关闭
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileWriter != null){
                    fileWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    /*
    * 实现文件的复制
    * */
    @Test
    public void testImgWriter(){
        FileWriter fileWriter = null;
        FileReader fileReader = null;
        try {
//        1.创建File对象,指明要对如和写出的文件
            File fileR = new File("src//top//oneluckyguy//pro//2.png");
            File fileW = new File("src//top//oneluckyguy//pro//3.png");
//        2.创建输入流和输出流的对象
            fileReader = new FileReader(fileR);
            fileWriter = new FileWriter(fileW);
//        3.数据的读入和写出操作
            char[] cbuffer = new char[5];
            int len;
            while ((len = fileReader.read(cbuffer)) != -1){
                for (int i = 0; i < len; i++) {
                    fileWriter.write(cbuffer[i]);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

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


    }

}

2.字节流输入输出流实现图片复制

package top.oneluckyguy.io;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Liu Qingfeng
 * @create 2020-12-19----15:11
 * 测试FileInputStream 和FileOutputStream的使用
 * 结论:
 *      对于文本文件使用字符流处理(.txt .doc .c .cpp .java)
 *      对于非文本文件使用字节流处理(视频 音频 .ppt)
 */
public class FileInputOutputStreamTest {
    //使用字节流处理文本文件是可能出现乱码的
    @Test
    public void testFileInputStream(){
        FileInputStream fileInputStream = null;
        try {
            //1.造文件
            File file = new File("hello.txt");
            //2.造流
            fileInputStream = new FileInputStream(file);
            //3.读数据
            byte[] cbuffer = new byte[5];
            int len = 0;
            while((len = fileInputStream.read(cbuffer)) != -1){
                String str = new String(cbuffer,0,len);
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    @Test
    public void testInputOutputStream(){
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            //1.造文件
            File fileI = new File("2.png");
            File fileO = new File("3.png");
            //2.造流
            fileInputStream = new FileInputStream(fileI);
            fileOutputStream = new FileOutputStream(fileO);
            //3.读写的过程
            byte[] buffer = new byte[5];
            int len;
            while((len = fileInputStream.read(buffer)) != -1){
                fileOutputStream.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fileOutputStream != null){
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fileInputStream != null){
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //指定路径下文件的复制
    public void copyFile(String srcPath,String destPath){
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            //1.造文件
            File fileI = new File(srcPath);
            File fileO = new File(destPath);
            //2.造流
            fileInputStream = new FileInputStream(fileI);
            fileOutputStream = new FileOutputStream(fileO);
            //3.读写的过程
            byte[] buffer = new byte[1024];
            int len;
            while((len = fileInputStream.read(buffer)) != -1){
                fileOutputStream.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fileOutputStream != null){
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fileInputStream != null){
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void testCopyFile(){
        long start = System.currentTimeMillis();
        copyFile("2.png","4.png");
        long end = System.currentTimeMillis();
        System.out.println("复制花费的时间:"+ (end - start));
    }
}

3.缓冲流实现文件复制,速度与节点流比较是否更快。

package top.oneluckyguy.io;

import org.junit.Test;

import java.io.*;

/**
 * @author Liu Qingfeng
 * @create 2020-12-19----16:44
 */
/*
* 实现非文本文件的复制
* */
public class BufferedTest {
    public void BufferedStreamTest (String srcPath,String destPath){
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            //1.造文件
            File filei = new File(srcPath);
            File fileo = new File(destPath);
            //2.造节点流
            fileInputStream = new FileInputStream(filei);
            fileOutputStream = new FileOutputStream(fileo);
//            3.造缓冲流
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            //4.操作
            byte[] buffer= new byte[1024];
            int len;
            while((len = bufferedInputStream.read(buffer)) != -1){
                bufferedOutputStream.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5.关闭流
            if (fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @Test
    public void fileBufferedCopyTest(){
        long start = System.currentTimeMillis();
        BufferedStreamTest("2.png","4.png");
        long end = System.currentTimeMillis();
        System.out.println("复制花费的时间:"+ (end - start));
    }
}

4.转换流的使用

InputStreamReader

OutputStreamwriter

package top.oneluckyguy.io;

import org.junit.Test;

import java.io.*;

/**
 * @author Liu Qingfeng
 * @create 2020-12-19----20:39
 * 处理流二:
 * 1.转换流:输入字符流
 * InputStreamReader 将一个字节的输入流转换为字符的输入流
 * OutputStreamWriter 将一个字符的输出流转化为字节的输出流
 * 2.作用:提供字节流与字符流之间的转换
 * 3.解码: 字节 字节数组----->字符数组 字符串
 *   编码: 字符数组 字符串----->字节 字节数组
 * 4.字符集
 *
 *
 */
public class InputStreamReaderTest {
    @Test
    public void test(){
        InputStreamReader inputStreamReader = null;
        try {
            File file = new File("hello.txt");
            FileInputStream fileInputStream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
            char[] cbuffer = new char[5];
            int len;
            while((len = inputStreamReader.read(cbuffer)) != -1){
                String str = new String(cbuffer,0,len);
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStreamReader != null){
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /*
    * 综合使用InputStreamReader 和OutputStreamWriter
    * 把utf-8文件以utf-8格式读入以gbk格式输出
    * */
    @Test
    public void testAll(){
        InputStreamReader inputStreamReader = null;
        OutputStreamWriter outputStreamWriter = null;
        try {
            File fileI = new File("hello.txt");
            File fileO = new File("rehello.txt");
            FileInputStream fileInputStream = new FileInputStream(fileI);
            FileOutputStream fileOutputStream = new FileOutputStream(fileO);
            inputStreamReader = new InputStreamReader(fileInputStream,"utf-8");
            outputStreamWriter = new OutputStreamWriter(fileOutputStream,"gbk");
            char[] cbuffer = new char[5];
            int len;
            while((len = inputStreamReader.read(cbuffer)) != -1){
                outputStreamWriter.write(cbuffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStreamReader != null){
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStreamWriter != null){
                try {
                    outputStreamWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

5.对象流

1.对String字符串进行序列化和反序列化的输入输出

package top.oneluckyguy.objectIO;

import org.junit.Test;

import java.io.*;

/**
 * @author Liu Qingfeng
 * @create 2020-12-20----15:29
 * 对象流的使用:
 * 1.ObjectInputStream和ObjectOutputStream
 * 2.作用:用于存储和读取基本数据类型数据或对象的处理流,
 * 3.要想一个Java对象是可序列化的,需要满足相应的要求:详见Person类
 */
public class ObjectInputOutputStreamTest {
    /*
    * 序列化过程,将内存中的Java对象保存到磁盘中或者通过网络传播出去
    * 使用ObjectOutputStram实现
    * */
    @Test
    public void testObjectOutputStream(){
        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(new FileOutputStream("hello.data"));
            objectOutputStream.writeObject(new String("坂井泉水"));
            objectOutputStream.flush();//把缓存中的数据刷新出去
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (objectOutputStream != null){
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /*
    * 反序列化,将磁盘文件中的对象还原为内存中的一个Java对象
    * 需要使用ObjectInputStream
    * */
    @Test
    public void testObjectInputStream(){
        ObjectInputStream objectInputStream = null;
        String str = null;
        try {
            objectInputStream = new ObjectInputStream(new FileInputStream("hello.data"));
            Object obj = objectInputStream.readObject();
            str = (String) obj;
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (objectInputStream != null){
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2.对Objec对象的序列化和反序列化

①对象类

package top.oneluckyguy.objectIO;

import java.io.Serializable;

/**
 * @author Liu Qingfeng
 * @create 2020-12-20----15:51
 */
public class Person implements Serializable {
    //这里如果不写UID系统会自动给你配一个UID,你序列化时用的UID必须和反序列化的UID一样
    //必须指定UID,如果不指定,对当前类修改的时候就会变化
    public static final long serialVersionUID = 12L;
    
    private String name;
    private int age;



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

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

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

    public int getAge() {
        return age;
    }

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

    public String getName() {
        return name;
    }
}

②处理流

package top.oneluckyguy.objectIO;

import org.junit.Test;
import java.io.*;

/**
 * @author Liu Qingfeng
 * @create 2020-12-20----15:29
 * 对象流的使用:
 * 1.ObjectInputStream和ObjectOutputStream
 * 2.作用:用于存储和读取基本数据类型数据或对象的处理流,
 * 3.要想一个Java对象是可序列化的,需要满足相应的要求:详见Person类
 *      1.需要实现接口:Serializable
 *      2.当前类需要提供一个全局常量serialVersionUID
 *      eg: public static final long serialVersionUID = -2228226523704288112L;
 *      3.除了当前Person类需要实现Serializable接口外还要保证其内部所有属性也必须是可序列化的。
 *      (默认情况下,基本数据类型都是可序列化的,同时String类型也是可序列化的)
 *      (如果Person类中有一个别的类Man作为Person类的参数,那么这个类Man也要可序列化实现Serializable接口和提供一个UID(这个UID和Person的不同))。
 * 补充:
 * ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
 * (不会报编译错误,但是数据不会保存。)
 */
public class ObjectInputOutputStreamTest {
    /*
    * 序列化过程,将内存中的Java对象保存到磁盘中或者通过网络传播出去
    * 使用ObjectOutputStram实现
    * */
    @Test
    public void testObjectOutputStream(){
        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(new FileOutputStream("hello.data"));
            objectOutputStream.writeObject(new String("坂井泉水"));
            objectOutputStream.flush();//把缓存中的数据刷新出去
            objectOutputStream.writeObject(new Person("大黑摩季",18));
            objectOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (objectOutputStream != null){
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /*
    * 反序列化,将磁盘文件中的对象还原为内存中的一个Java对象
    * 需要使用ObjectInputStream
    * */
    @Test
    public void testObjectInputStream(){
        ObjectInputStream objectInputStream = null;
        String str = null;
        Person person = null;
        try {
            objectInputStream = new ObjectInputStream(new FileInputStream("hello.data"));
            Object obj = objectInputStream.readObject();
            str = (String) obj;

            Object objects =  objectInputStream.readObject();
            person = (Person) objects;

            System.out.println(str);
            System.out.println(person);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (objectInputStream != null){
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值