nio 基本用法
java.nio.file.Files;
createDirectory - 创建目录
示例
public void init() {
try {
Path rootLocation = Paths.get("/tmp");
Files.createDirectory(rootLocation);
} catch (IOException e) {
throw new StorageException("Could not initialize storage", e);
}
}
copy - 复制文件到指定路径
示例
public void store(MultipartFile file) {
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file " + file.getOriginalFilename());
}
Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
} catch (IOException e) {
throw new StorageException("Failed to store file " + file.getOriginalFilename(), e);
}
}
其中,Path 的 resolve方法:根据文件名中解析得到完整Path。
walk - 遍历指定路径下的文件到流中(可以通过 json返回给页面)
public static java.util.stream.Stream<java.nio.file.Path> walk(java.nio.file.Path start,
int maxDepth,
@NotNull java.nio.file.FileVisitOption... options)
throws java.io.IOException
示例
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(this.rootLocation::relativize);
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
其中,Stream的 filter 和 map方法:对Stream进行一些修正。
FileSystemUtils - springframework 的工具类,递归删除
public void deleteAll() {
FileSystemUtils.deleteRecursively(rootLocation.toFile());
}
--
项目地址 http://git.oschina.net/lemosd/gs-uploading-files
来源:oschina
链接:https://my.oschina.net/u/3053700/blog/885461