jimfs:Java内存文件系统,脱离磁盘IO瓶颈利器
一、写在前面
开源地址:https://github.com/google/jimfs
Jimfs由Google发布,实现了 java.nio.file
接口,支持模拟不同操作系统的文件系统特性(如 Windows/Linux 路径风格)。
主要用于单元测试(避免磁盘 IO 影响速度和状态)、临时数据处理(短期缓存、中间计算结果)和环境隔离(多任务互不干扰)
等场景。
<dependency><groupId>com.google.jimfs</groupId><artifactId>jimfs</artifactId><version>1.3.1</version>
</dependency>
二、使用
1、基本使用
import com.google.common.collect.ImmutableList;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;public class Test {public static void main(String[] args) throws Exception {// Linux系统目录FileSystem fs = Jimfs.newFileSystem(Configuration.unix());Path foo = fs.getPath("/foo");Files.createDirectory(foo);// 写入hello.txtPath hello = foo.resolve("hello.txt"); // /foo/hello.txtFiles.write(hello, ImmutableList.of("hello world"), StandardCharsets.UTF_8);// 读取List<String> lines = Files.readAllLines(hello, StandardCharsets.UTF_8);for (String line : lines) {System.out.println(line);}}
}
2、注意
jimfs只能使用java.nio
相关的API,不过这已经足够。
其他更多使用方式参考java.nio.file.Files
即可