java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java读写文件

Java使用字节流、缓冲流、转换流与对象流读写文件的示例代码

作者:连杰李

这段文章详细介绍了Java中的流及其分类,涵盖了字节流、缓冲流和转换流等核心概念,文章还阐述了如何使用这些流进行文件读写操作,包括字节流、缓冲流、转换流和对象流的使用方法,需要的朋友可以参考下

一、Java 中有哪些流

二、Java 中流的分类

三、Java 中流如何使用

四、使用字节流读写文件

    public void copyFileWithFile(String srcPath, String destPath) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //1.
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);
            //2.
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);

            //3. 读写过程
            int len;
            byte[] buffer = new byte[100];
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. 关闭资源
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

五、使用缓冲流读写文件

    public void copyFileWithBuffered(String srcPath, String destPath) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //1.
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);
            //2.
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(destFile);

            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            //3. 读写过程
            int len;
            byte[] buffer = new byte[100];
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. 关闭资源(1. 需要先关闭缓冲流,再关闭文件流 2. 默认情况下,关闭外层流时,也会自动关闭内部的流)
            try {
                if(bos != null)
                    bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(bis != null)
                    bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //可以省略
//        fos.close();
//        fis.close();
        }

    }

六、字符流只能读写文本文件

    public void test() {
        InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        try {
            isr = new InputStreamReader(new FileInputStream("康师傅的话.txt"),"gbk");

            osw = new OutputStreamWriter(new FileOutputStream("C:\\Users\\shkstart\\Desktop\\寄语.txt"),"utf-8");

            char[] cbuf = new char[1024];
            int len;
            while ((len = isr.read(cbuf)) != -1) {
                osw.write(cbuf, 0, len);
                osw.flush();
            }
            System.out.println("文件复制完成");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (isr != null)
                    isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (osw != null)
                    osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

七、使用转换流进行解码编码

使用 UTF8 解码文件得到文件内容后使用 GBK 编码文件输出到新的文件中

    public void test4() {
        InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        try {
            //1. 造文件
            File file1 = new File("dbcp_gbk.txt");
            File file2 = new File("dbcp_gbk_to_utf8.txt");

            //2. 造流
            FileInputStream fis = new FileInputStream(file1);
            //参数2对应的是解码集,必须与dbcp_gbk.txt的编码集一致。
            isr = new InputStreamReader(fis,"GBK");


            FileOutputStream fos = new FileOutputStream(file2);
            //参数2指明内存中的字符存储到文件中的字节过程中使用的编码集。
            osw = new OutputStreamWriter(fos,"utf8");

            //3. 读写过程
            char[] cBuffer = new char[1024];
            int len;
            while((len = isr.read(cBuffer)) != -1){
                osw.write(cBuffer,0,len);
            }

            System.out.println("操作完成");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //4. 关闭资源
            try {
                if(osw != null)
                    osw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                if(isr != null)
                    isr.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

八、使用对象流序列化反序列化

person 对象

package com.atguigu05.objectstream;
import java.io.Serializable;

public class Person implements Serializable { //Serializable:属于一个标识接口
    String name;
    int age;

    int id;

    Account acct;

    static final long serialVersionUID = 422334254234L;

    public Person() {
    }

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

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

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

    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;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", id=" + id +
                ", acct=" + acct +
                '}';
    }
}

class Account implements Serializable{
    double balance;

    static final long serialVersionUID = 422234L;

    public Account(double balance) {
        this.balance = balance;
    }

    @Override
    public String toString() {
        return "Account{" +
                "balance=" + balance +
                '}';
    }
}

序列化 person 对象

    public void test3(){
        ObjectOutputStream oos = null;
        try {
            File file = new File("object1.dat");
            oos = new ObjectOutputStream(new FileOutputStream(file));

            //2.写出数据即为序列化的过程
            Person p1 = new Person("Tom",12);
            oos.writeObject(p1);
            oos.flush();

            Person p2 = new Person("Jerry",23,1001,new Account(2000));
            oos.writeObject(p2);
            oos.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(oos != null)
                    oos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

反序列化 person 对象

    public void test4() {
        ObjectInputStream ois = null;
        try {
            File file = new File("object1.dat");
            ois = new ObjectInputStream(new FileInputStream(file));

            //2. 读取文件中的对象(或反序列化的过程)
            Person person = (Person) ois.readObject();
            System.out.println(person);

            Person person1 = (Person) ois.readObject();
            System.out.println(person1);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(ois != null)
                    ois.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

以上就是Java使用字节流、缓冲流、转换流与对象流读写文件的示例代码的详细内容,更多关于Java读写文件的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文