nio 基本用法git
java.nio.file.Files;
示例spring
public void init() { try { Path rootLocation = Paths.get("/tmp"); Files.createDirectory(rootLocation); } catch (IOException e) { throw new StorageException("Could not initialize storage", e); } }
示例apache
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。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
示例ide
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進行一些修正。工具
public void deleteAll() { FileSystemUtils.deleteRecursively(rootLocation.toFile()); }
--ui