Java文件读写(IO、NIO)

发布于:2025-08-09 ⋅ 阅读:(16) ⋅ 点赞:(0)

1. 传统阻塞式 I/O(java.io)分类

  1. 基类 InputStream、OutputStream
  2. 字节流 FileInputStream、OutputStream
  3. 字节缓冲流 BufferedInputStream、BufferedOutputStream
  4. 字符流 FileWriter、FileReader
  5. 字符缓冲流 BufferedWriter、BufferedReader

字符流用来处理文本,字节流用来处理除文本外的文件。
缓冲流作为装饰器提升效率,内部实现缓冲区,缓冲区满了之后发送。

2. IO示例

import java.io.*;

/**
 * 文件读写
 * 0、基类 InputStream、OutputStream
 * 1、字节流 FileInputStream、OutputStream
 * 2、字节缓冲流 BufferedInputStream、BufferedOutputStream
 * 3、字符流 FileWriter、FileReader
 * 4、字符缓冲流 BufferedWriter、BufferedReader
 * 5、缓冲流作为装饰器提升效率,内部实现缓冲区,缓冲区满了之后发送
 */
public class Test_IO {
    public static void main(String[] args) {
        test_character_writer();

        test_character_reader();

        byte[] bytes = test_byte_reader();

        test_byte_writer(bytes);
    }

    public static void test_character_writer() {
        // 字符流-写入
        try{
            File file = new File("resources/云深不知处.txt");
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            // 第二个参数true,不覆盖原文,末尾添加内容
            // BufferedWriter bufferedWriter = new BufferedWriter(fileWriter, true);
            bufferedWriter.write("松下问童子,\n言师采药去。\n只在此山中,\n云深不知处。");
            bufferedWriter.close();
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void test_character_reader() {
        // 字符流-读取
        try{
            FileReader fileReader = new FileReader("resources/云深不知处.txt");
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            bufferedReader.close();
            fileReader.close();
            System.out.println(stringBuilder.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static byte[] test_byte_reader() {
        // 字节流 - 读取
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        try {
            FileInputStream fileInputStream = new FileInputStream("resources/lkm.png");
            BufferedInputStream bis = new BufferedInputStream(fileInputStream);

            byte[] buffer = new byte[1024];
            int bytesRead;
            while((bytesRead = bis.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }

            bis.close();
            fileInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        byte[] bytes = byteArrayOutputStream.toByteArray();

        return bytes;
    }

    public static void test_byte_writer(byte[] bytes) {
        // 字节流-写入
        try{
            File file = new File("resources/lkm2.png");
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
            bos.write(bytes);
            bos.close();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. Java NIO(New I/O)

在 JDK 1.4 中首次引入的,作为对传统阻塞式 I/O(java.io)的一次重大改进,提供了更高效、非阻塞的 I/O 操作能力。NIO 的核心组件包括 Buffer、Channel 和 Selector,这些组件使得开发者能够构建高性能、可扩展的网络和文件 I/O 应用程序。

NIO 的引入极大地增强了 Java 对 I/O 操作的控制能力,特别是在处理大量并发连接或进行大文件读写时,其性能优势明显优于传统的 I/O 模型。随着 JDK 的演进,NIO 在后续版本中不断被增强,例如 JDK 1.7 引入了 NIO 2.0(也称为 JSR 203),增加了对异步 I/O 的支持,以及对文件系统和路径操作的增强功能。

字符流
  1. Files.write
  2. Files.readAllLine
字节流
  1. Files.write
  2. Files.readAllBytes

Files 类的方法在执行文件读写时,虽然不直接暴露缓冲流(如 BufferedReader 或 BufferedInputStream)的使用,但在底层实现中确实采用了类似缓冲机制来提高性能。
因此,不需要考虑缓冲流的问题。

4. NIO示例

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;

public class Test_NIO {
    public static void main(String[] args) {
        test_character_writer();

        test_character_reader();

        byte[] bytes = test_byte_reader();

        test_byte_writer(bytes);
    }

    public static void test_character_writer() {
        // 字符流-写入
        String s = "松下问童子,\n言师采药去。\n只在此山中,\n云深不知处。";
        try {
            Files.write(Paths.get("resources/云深不知处.txt"), Collections.singleton(s));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void test_character_reader() {
        // 字符流-读取
        try {
            List<String> list = Files.readAllLines(Paths.get("resources/云深不知处.txt"));
            String s = list.stream().reduce("", (a, b) -> a + b);
            System.out.println(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static byte[] test_byte_reader() {
        // 字节流 - 读取
        byte[] bytes = new byte[0];
        try {
            bytes = Files.readAllBytes(Paths.get("resources/lkm.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bytes;
    }

    public static void test_byte_writer(byte[] bytes) {
        // 字节流-写入
        try {
            Files.write(Paths.get("resources/lkm2.png"), bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到