Java内存文件系统:Jimfs
jopen
10年前
Jimfs 是一个用于 Java 7+ 的内存中的文件系统,实现了 java.nio.file 抽象文件系统 API。Jimfs 支持几乎所有 java.nio.file下的APIs。它支持:
- 创建,删除,移动和复制文件与目录
利用 FileChannel
或 SeekableByteChannel
,InputStream
,OutputStream
等读写文件.- Symbolic links.
- Hard links to regular files.
SecureDirectoryStream
, for operations relative to an open directory.- Glob and regex path filtering with
PathMatcher
. - Watching for changes to a directory with a
WatchService
. - File attributes. Built-in attribute views that can be supported include "basic", "owner", "posix", "unix", "dos", "acl" and "user". Do note, however, that not all attribute views provideuseful attributes. For example, while setting and reading POSIX file permissions is possible with the "posix" view, those permissions will not actually affect the behavior of the file system.
Jimfs 还支持创建文件系统,for example, use Windows-style paths and (to an extent) behavior. In general, however, file system behavior is modeled after UNIX and may not exactly match any particular real file system or platform.
Maven
<dependency> <groupId>com.google.jimfs</groupId> <artifactId>jimfs</artifactId> <version>1.0</version> </dependency>
基本用法
最简单的用法是使用Jimfs来取得一个新的FileSystem
实例,从 Jimfs
类:
import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; ... // For a simple file system with Unix-style paths and behavior: FileSystem fs = Jimfs.newFileSystem(Configuration.unix()); Path foo = fs.getPath("/foo"); Files.createDirectory(foo); Path hello = foo.resolve("hello.txt"); // /foo/hello.txt Files.write(hello, ImmutableList.of("hello world"), StandardCharsets.UTF_8);