java的文件读写

Java中如何以二进制字节的方式来处理文件,前面我们提到Java中有流的概念,以二进制方式读写的主要流有:❑ InputStream/OutputStream:这是基类,它们是抽象类。❑ FileInputStream/FileOutputStream:输入源和输出目标是文件的流。❑ ByteArrayInputStream/ByteArrayOutputStream:输入源和输出目标是字节数组的流。❑ DataInputStream/DataOutputStream:装饰类,按基本类型和字符串而非只是字节读写流。❑ BufferedInputStream/BufferedOutputStream:装饰类,对输入输出流提供缓冲功能。下面,我们就来介绍这些类的功能、用法、原理和使用场景,最后总结一些简单的实用方法。

下面举个列子

package com.wcfb.model.po;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @author wcfb
 * @time 2021/5/8/008.
 * @since
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class StudentPO implements Serializable {
    private String name;
    private int age;
    private int sex;
}
package com.wcfb;

import com.wcfb.model.po.StudentPO;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author wcfb
 * @time 2021/5/8/008.
 * @desc 文件流测试
 * @since 1.0
 */
@SpringBootTest
public class FileTestApplication {

    /**
     * 写内容到文件
     *
     * @throws IOException
     */
    @Test
    public void test1() throws IOException {
        OutputStream outputStream = new FileOutputStream("text.txt");
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 1000; i++) {
            stringBuilder.append("hello io ").append(i).append("\n");
        }
        String data = stringBuilder.toString();
        byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
        try {
            outputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            outputStream.close();
        }
    }

    /**
     * 读取文件内容(固定长度)
     *
     * @throws IOException
     */
    @Test
    public void test2() throws IOException {
        InputStream inputStream = new FileInputStream("text.txt");
        byte[] buf = new byte[1024];
        try {
            int byteRead = inputStream.read(buf);
            String data = new String(buf, 0, byteRead, StandardCharsets.UTF_8);
            System.out.println(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            inputStream.close();
        }
    }

    /**
     * 读取所有内容
     */
    @Test
    public void test3() throws Exception {
        InputStream inputStream = new FileInputStream("text.txt");
        byte[] buf = new byte[1024];
        int byteRead = -1;
        while ((byteRead = inputStream.read(buf)) != -1) {
            String data = new String(buf, 0, byteRead, StandardCharsets.UTF_8);
            System.out.println(data);
        }
    }

    /**
     * 保存对象
     *
     * @throws FileNotFoundException
     */
    @Test
    public void test4() throws Exception {
        List studentList = Arrays.asList(
                new StudentPO("小红", 16, 0),
                new StudentPO("小兰", 17, 1),
                new StudentPO("小黑", 22, 1)
        );
        DataOutput dataOutput = new DataOutputStream(new FileOutputStream("student.txt"));
        for (StudentPO s : studentList) {
            dataOutput.writeUTF(s.getName());
            dataOutput.writeInt(s.getAge());
            dataOutput.writeInt(s.getSex());
        }
    }

    /**
     * 读取对象(文件流格式)
     */
    @Test
    public void test5() throws Exception {
        DataInput input = new DataInputStream(new FileInputStream("student.txt"));
        List studentList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            studentList.add(new StudentPO(input.readUTF(), input.readInt(), input.readInt()));
        }
        studentList.forEach(System.out::println);
    }

    /**
     * 使用writer
     */
    @Test
    public void test6() throws Exception {
        Writer writer = new OutputStreamWriter(new FileOutputStream("student.txt"), StandardCharsets.UTF_8);
        String data = "hello io 试试";
        try {
            writer.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }

    /**
     * 使用reader
     */
    @Test
    public void test7() throws Exception {
        Reader reader = new InputStreamReader(new FileInputStream("student.txt"), StandardCharsets.UTF_8);
        try {
            char[] cbuf = new char[1024];
            int chatsRead = reader.read(cbuf);
            System.out.println(new String(cbuf, 0, chatsRead));
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            reader.close();
        }
    }

    /**
     * fileWriter使用
     *
     * @throws Exception
     */
    @Test
    public void test8() throws Exception {
        Writer writer = new FileWriter("student.txt");
        try {
            writer.write("writer is ok a");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }

    /**
     * 使用 fileReader
     *
     * @throws Exception
     */
    @Test
    public void test9() throws Exception {
        Reader reader = new FileReader(new File("student.txt"));
        try {
            char[] chars = new char[1024];
            int read = reader.read(chars);
            System.out.println(new String(chars));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    /**
     * fileWriter使用
     *
     * @throws Exception
     */
    @Test
    public void test8() throws Exception {
        Writer writer = new FileWriter("student.txt");
        try {
            writer.write("writer is ok a");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }


        Reader reader = new FileReader(new File("student.txt"));
        try {
            char[] chars = new char[1024];
            int read = reader.read(chars);
            System.out.println(new String(chars));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }


    /**
     * 使用bufferWriter
     *
     * @throws Exception
     */
    @Test
    public void test10() throws Exception {
        BufferedWriter writer = new BufferedWriter(new FileWriter("student.txt"));
        try {
            writer.write("你好," + "hhhh 哈哈哈\n guguhhhh ");
            writer.newLine();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }

        BufferedReader reader = new BufferedReader(new FileReader("student.txt"));
        try {
            String s = null;
            while ((s = reader.readLine()) != null) {
                System.out.println(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reader.close();
        }
    }

}

用例1 生成的文件对应的截图如下


image.png

用例2生成的截图如下


image.png

用例3的截图如下
image.png

用例6的截图如下


image.png

用例7的截图如下
image.png

小结

本节介绍了如何在Java中以字符流的方式读写文本文件,我们强调了二进制思维、文本文本与二进制文件的区别、编码,以及字符流与字节流的不同,介绍了个各种字符流、Scanner以及标准流,最后总结了一些实用方法。写文件时,可以优先考虑PrintWriter,因为它使用方便,支持自动缓冲、指定编码类型、类型转换等。读文件时,如果需要指定编码类型,需要使用InputStreamReader;如果不需要指定编码类型,可使用FileReader,但都应该考虑在外面包上缓冲类Buffered-Reader。

你可能感兴趣的:(java的文件读写)