练习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,和 SpringResource.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();
}
}
}
要点
try(InputStream in = ...)代码结束自动 close,不用手动写in.close(),避免句柄泄露in.read(buffer)返回-1= 流读到末尾InputStream是一次性流,读完之后不能重复读取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();
}
}
}
自测
- 新建
test.txt,运行练习1写入内容 - 运行练习2,通过字节流读取并打印
- 修改代码:增加
if(!Files.exists(path))判断文件是否存在,不存在直接提示 - 运行练习3,通过字节流写入文件
浙公网安备 33010602011771号