List of usage examples for java.nio.file Files delete
public static void delete(Path path) throws IOException
From source file:de.ingrid.interfaces.csw.tools.FileUtils.java
/** * Delete a file or directory specified by a {@link Path}. This method uses * the new {@link Files} API and allows to specify a regular expression to * remove only files that match that expression. * /*from w w w . ja v a 2 s.com*/ * @param path * @param pattern * @throws IOException */ public static void deleteRecursive(Path path, final String pattern) throws IOException { final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:" + pattern); if (!Files.exists(path)) return; Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (pattern != null && matcher.matches(file.getFileName())) { Files.delete(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { // try to delete the file anyway, even if its attributes // could not be read, since delete-only access is // theoretically possible if (pattern != null && matcher.matches(file.getFileName())) { Files.delete(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc == null) { if (matcher.matches(dir.getFileName())) { if (dir.toFile().list().length > 0) { // remove even if not empty FileUtils.deleteRecursive(dir); } else { Files.delete(dir); } } return FileVisitResult.CONTINUE; } else { // directory iteration failed; propagate exception throw exc; } } }); }
From source file:org.sakuli.actions.screenbased.ScreenshotActions.java
/** * Transfers a {@link BufferedImage} to an picture and saves it * * @param pictureFile Path to the final image * @return {@link Path} ot the screenshot. *//*ww w .j a v a2s. co m*/ static Path createPictureFromBufferedImage(Path pictureFile, String screenshotFormat, BufferedImage bufferedImage) throws IOException { Path absPath = pictureFile.normalize().toAbsolutePath(); //check Folder if (!Files.exists(absPath.getParent())) { Files.createDirectory(absPath.getParent()); } if (Files.exists(absPath)) { LOGGER.info("overwrite screenshot '{}'", absPath); Files.delete(absPath); } Files.createFile(pictureFile); OutputStream outputStream = Files.newOutputStream(pictureFile); if (!allowedScreenshotFormats.contains(screenshotFormat)) { throw new IOException("Format '" + screenshotFormat + "' is not supported! Use " + allowedScreenshotFormats.toString()); } //write image ImageIO.write(bufferedImage, screenshotFormat, outputStream); LOGGER.info("screen shot saved to file \"" + pictureFile.toFile().getAbsolutePath() + "\""); return pictureFile; }
From source file:company.gonapps.loghut.utils.FileUtils.java
public static void rmdir(Path directoryPath, DirectoryStream.Filter<Path> ignoringFilter) throws NotDirectoryException, IOException { if (!directoryPath.toFile().isDirectory()) throw new NotDirectoryException(directoryPath.toString()); try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directoryPath)) { List<Path> ignoredPaths = new LinkedList<>(); for (Path path : directoryStream) { if (!ignoringFilter.accept(path)) return; ignoredPaths.add(path);/* www . j a v a2 s . co m*/ } for (Path ignoredPath : ignoredPaths) { Files.delete(ignoredPath); } Files.delete(directoryPath); } }
From source file:org.forgerock.openidm.maintenance.upgrade.StaticFileUpdateTest.java
@AfterMethod public void deleteTempFile() throws IOException { Files.deleteIfExists(tempFile.resolveSibling(getNewVersionPath(tempFile))); Files.deleteIfExists(tempFile.resolveSibling(getOldVersionPath(tempFile))); Files.delete(tempFile); }
From source file:com.fujitsu.dc.core.model.file.StreamingOutputForDavFileWithRange.java
@Override public void write(OutputStream output) throws IOException, WebApplicationException { try {/*from www . ja va2 s . c o m*/ // MultiPart???????1?byte-renge-set???? int rangeIndex = 0; List<ByteRangeSpec> brss = range.getByteRangeSpecList(); final ByteRangeSpec brs = brss.get(rangeIndex); int chr; long first = brs.getFirstBytePos(); long last = brs.getLastBytePos(); // Range?????? if (hardLinkInput.skip(first) != first) { DcCoreLog.Dav.FILE_TOO_SHORT.params("skip failed", fileSize, range.getRangeHeaderField()) .writeLog(); throw DcCoreException.Dav.FS_INCONSISTENCY_FOUND; } // Range???? for (long pos = first; pos < last + 1; pos++) { chr = hardLinkInput.read(); if (chr == -1) { DcCoreLog.Dav.FILE_TOO_SHORT.params("too short.size", fileSize, range.getRangeHeaderField()) .writeLog(); throw DcCoreException.Dav.FS_INCONSISTENCY_FOUND; } output.write((char) chr); } } finally { IOUtils.closeQuietly(hardLinkInput); Files.delete(hardLinkPath); } }
From source file:org.fim.tooling.RepositoryTool.java
public void createFimIgnore(Path directory, String content) throws IOException { Path file = directory.resolve(".fimignore"); if (Files.exists(file)) { Files.delete(file); }/* ww w . ja v a2 s. c om*/ Files.write(file, content.getBytes(), CREATE); }
From source file:com.autoupdater.server.services.FileServiceImp.java
@Override public void removeFile(String storagePath) { logger.debug("Attempting to remove File: " + storagePath); try {// www . ja va 2 s.com Files.delete(Paths.get(getStorageDirectory() + storagePath)); } catch (IOException e) { logger.error("Couldn't locate file: " + storagePath); return; } logger.debug("File removed: " + storagePath); }
From source file:org.nuxeo.ecm.core.blob.TestFilesystemBlobProvider.java
@After public void tearDown() throws Exception { if (tmpFile != null && Files.exists(tmpFile)) { Files.delete(tmpFile); } }
From source file:io.lavagna.web.api.ExportImportController.java
@RequestMapping(value = "/api/import/lavagna", method = RequestMethod.POST) @ResponseBody/*from ww w .j a va 2 s . c o m*/ public void importFromLavagna( @RequestParam(value = "overrideConfiguration", defaultValue = "false") Boolean overrideConfiguration, @RequestParam("file") MultipartFile file) throws IOException { Path tempFile = Files.createTempFile(null, null); try { try (InputStream is = file.getInputStream(); OutputStream os = Files.newOutputStream(tempFile)) { StreamUtils.copy(is, os); } exportImportService.importData(overrideConfiguration, tempFile); } finally { Files.delete(tempFile); } }
From source file:org.savantbuild.io.tar.TarTools.java
/** * Untars a TAR file. This also handles tar.gz files by checking the file extension. If the file extension ends in .gz * it will read the tarball through a GZIPInputStream. * * @param file The TAR file.//ww w .j a v a 2s . c o m * @param to The directory to untar to. * @param useGroup Determines if the group name in the archive is used. * @param useOwner Determines if the owner name in the archive is used. * @throws IOException If the untar fails. */ public static void untar(Path file, Path to, boolean useGroup, boolean useOwner) throws IOException { if (Files.notExists(to)) { Files.createDirectories(to); } InputStream is = Files.newInputStream(file); if (file.toString().endsWith(".gz")) { is = new GZIPInputStream(is); } try (TarArchiveInputStream tis = new TarArchiveInputStream(is)) { TarArchiveEntry entry; while ((entry = tis.getNextTarEntry()) != null) { Path entryPath = to.resolve(entry.getName()); if (entry.isDirectory()) { // Skip directory entries that don't add any value if (entry.getMode() == 0 && entry.getGroupName() == null && entry.getUserName() == null) { continue; } if (Files.notExists(entryPath)) { Files.createDirectories(entryPath); } if (entry.getMode() != 0) { Set<PosixFilePermission> permissions = FileTools.toPosixPermissions(entry.getMode()); Files.setPosixFilePermissions(entryPath, permissions); } if (useGroup && entry.getGroupName() != null && !entry.getGroupName().trim().isEmpty()) { GroupPrincipal group = FileSystems.getDefault().getUserPrincipalLookupService() .lookupPrincipalByGroupName(entry.getGroupName()); Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setGroup(group); } if (useOwner && entry.getUserName() != null && !entry.getUserName().trim().isEmpty()) { UserPrincipal user = FileSystems.getDefault().getUserPrincipalLookupService() .lookupPrincipalByName(entry.getUserName()); Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setOwner(user); } } else { if (Files.notExists(entryPath.getParent())) { Files.createDirectories(entryPath.getParent()); } if (Files.isRegularFile(entryPath)) { if (Files.size(entryPath) == entry.getSize()) { continue; } else { Files.delete(entryPath); } } Files.createFile(entryPath); try (OutputStream os = Files.newOutputStream(entryPath)) { byte[] ba = new byte[1024]; int read; while ((read = tis.read(ba)) != -1) { if (read > 0) { os.write(ba, 0, read); } } } if (entry.getMode() != 0) { Set<PosixFilePermission> permissions = FileTools.toPosixPermissions(entry.getMode()); Files.setPosixFilePermissions(entryPath, permissions); } if (useGroup && entry.getGroupName() != null && !entry.getGroupName().trim().isEmpty()) { GroupPrincipal group = FileSystems.getDefault().getUserPrincipalLookupService() .lookupPrincipalByGroupName(entry.getGroupName()); Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setGroup(group); } if (useOwner && entry.getUserName() != null && !entry.getUserName().trim().isEmpty()) { UserPrincipal user = FileSystems.getDefault().getUserPrincipalLookupService() .lookupPrincipalByName(entry.getUserName()); Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setOwner(user); } } } } }