万金流
以码会友。 吾Q:578751655。 水平有限,轻喷,谢!

练习1:NIO.2 读写文本文件

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Nio2TextDemo {
    public static void main(String[] args) throws IOException {
        // 1. 构造路径对象
        var filePath = Paths.get("test.txt");

        // 写入文本(UTF-8),文件不存在则新建,存在则覆盖
        String writeContent = "Hello NIO.2\nSpring Pre Learn";
        Files.writeString(filePath, writeContent, StandardCharsets.UTF_8);

        // 读取文本
        String readContent = Files.readString(filePath, StandardCharsets.UTF_8);
        System.out.println("读取内容:");
        System.out.println(readContent);
    }
}

练习2:NIO.2 获取 InputStream + try-with-resources

核心:Files.newInputStream 返回 java.io.InputStream,和 Spring Resource.getInputStream() / MultipartFile.getInputStream() 是同一个类型

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;

public class Nio2StreamDemo {
    public static void main(String[] args) {
        var path = Paths.get("test.txt");

        // try-with-resources:自动关闭InputStream,AutoCloseable
        try (InputStream in = Files.newInputStream(path)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) != -1) {
                String str = new String(buffer, 0, len, StandardCharsets.UTF_8);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

要点

  1. try(InputStream in = ...) 代码结束自动 close,不用手动写 in.close(),避免句柄泄露
  2. in.read(buffer) 返回 -1 = 流读到末尾
  3. InputStream 是一次性流,读完之后不能重复读取
  4. Paths.get() 只是路径描述,不代表文件一定存在;可用 Files.exists(path) 判断

练习3:NIO.2 获取 OutStream + try-with-resources

OutputStream:反向管子,写文件。原理和 InputStream 对称。Spring 下载就是往 OutputStream 写。

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;

public class Nio2StreamWriteDemo {
    public static void main(String[] args) {
        var path = Paths.get("test.txt");

        // try-with-resources:自动关闭OutputStream,AutoCloseable
        try (OutputStream out = Files.newOutputStream(path)) {
            String content = "Hello, JDK 25! 这是要写入的内容。";
            byte[] buffer = content.getBytes(StandardCharsets.UTF_8);
            out.write(buffer, 0, buffer.length);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

自测

  1. 新建 test.txt,运行练习1写入内容
  2. 运行练习2,通过字节流读取并打印
  3. 修改代码:增加 if(!Files.exists(path)) 判断文件是否存在,不存在直接提示
  4. 运行练习3,通过字节流写入文件
posted on 2026-09-12 20:23  万金流  阅读(39)  评论(0)    收藏  举报