Example usage for java.nio.file Files delete

List of usage examples for java.nio.file Files delete

Introduction

In this page you can find the example usage for java.nio.file Files delete.

Prototype

public static void delete(Path path) throws IOException 

Source Link

Document

Deletes a file.

Usage

From source file:org.apache.tika.parser.jdbc.SQLite3DBParser.java

@Override
public void close() throws SQLException, IOException {
    try {/*www.  j a v  a2s . com*/
        super.close();
    } finally {
        if (tmpFile != null) {
            Files.delete(tmpFile);
        }
    }
}

From source file:com.spotify.docker.client.CompressedDirectory.java

/**
 * This method creates a gzip tarball of the specified directory. File permissions will be
 * retained. The file will be created in a temporary directory using the {@link
 * Files#createTempFile(String, String, FileAttribute[])} method. The returned object is
 * auto-closeable, and upon closing it, the archive file will be deleted.
 *
 * @param directory the directory to compress
 * @return a Path object representing the compressed directory
 * @throws IOException if the compressed directory could not be created.
 *//*w  ww . j ava2 s .  c om*/
public static CompressedDirectory create(final Path directory) throws IOException {
    final Path file = Files.createTempFile("docker-client-", ".tar.gz");

    final Path dockerIgnorePath = directory.resolve(".dockerignore");
    final ImmutableSet<PathMatcher> ignoreMatchers = parseDockerIgnore(dockerIgnorePath);

    try (final OutputStream fileOut = Files.newOutputStream(file);
            final GzipCompressorOutputStream gzipOut = new GzipCompressorOutputStream(fileOut);
            final TarArchiveOutputStream tarOut = new TarArchiveOutputStream(gzipOut)) {
        tarOut.setLongFileMode(LONGFILE_POSIX);
        tarOut.setBigNumberMode(BIGNUMBER_POSIX);
        Files.walkFileTree(directory, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                new Visitor(directory, ignoreMatchers, tarOut));

    } catch (Throwable t) {
        // If an error occurs, delete temporary file before rethrowing exception.
        try {
            Files.delete(file);
        } catch (IOException e) {
            // So we don't lose track of the reason the file was deleted... might be important
            t.addSuppressed(e);
        }

        throw t;
    }

    return new CompressedDirectory(file);
}

From source file:it.infn.ct.futuregateway.apiserver.storage.LocalStorage.java

@Override
public final void removeAllFiles(final RESOURCE res, final String id) throws IOException {
    java.nio.file.Path filePath = Paths.get(path, res.name().toLowerCase(), id);
    if (Files.notExists(filePath)) {
        return;/*from   w  ww.j  a v a 2 s .co  m*/
    }
    if (Files.isDirectory(filePath)) {
        Files.walkFileTree(filePath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult postVisitDirectory(final Path dir, final IOException exc)
                    throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                    throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    Files.delete(filePath);
}

From source file:ufo.test.spark.service.WordCountServiceTest.java

private void deleteRecursively(Path path) throws IOException {
    if (Files.exists(path)) {
        //delete recursively
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override/*  ww w. j av  a2s  .  c o m*/
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    assertFalse(Files.exists(path));
}

From source file:org.esa.nest.util.FileIOUtils.java

public static void deleteFolder(final Path source) throws IOException {
    Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
        @Override//from w  w w .  j  a  va2  s .  c  o m
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            if (exc == null) {
                Files.delete(dir);
                return CONTINUE;
            } else {
                throw exc;
            }
        }
    });
}

From source file:org.apache.taverna.robundle.manifest.TestManifestJSON.java

@Test
public void testHistory() throws IOException {
    Path tmpBundle = Files.createTempFile("testbundle", "history");

    // create history
    try (Bundle bundle = Bundles.createBundle()) {
        Bundles.closeAndSaveBundle(bundle, tmpBundle);
    } catch (IOException e) {
        fail("failed to create bundle for history test: " + e.getMessage());
    }//from ww  w  . ja  v a 2 s .c o m

    // make sure it doesn't fail if there is no history
    try (Bundle bundle = Bundles.openBundle(tmpBundle)) {
        Manifest manifest = bundle.getManifest();
        Path evolutionPath = bundle.getPath(".ro/evolution.ttl");
        assertFalse("did not expect a history file", Files.exists(evolutionPath));
        assertEquals("did not expect a history", 0, manifest.getHistory().size());

        Files.createDirectories(evolutionPath.getParent());
        Bundles.setStringValue(evolutionPath, "<manifest.json> < http://purl.org/pav/retrievedFrom> "
                + "<http://wf4ever.github.io/ro/bundle/2013-05-21/example/.ro/manifest.json> .");
        manifest.getHistory().add(evolutionPath);
        assertTrue("expected a history file", Files.exists(evolutionPath));
        assertTrue("expected a history", manifest.getHistory().size() > 0);

        Bundles.closeBundle(bundle);
    } catch (IOException e) {
        fail("failed to read bundle for history test: " + e.getMessage());
    }

    // check if history is still there
    try (Bundle bundle = Bundles.openBundleReadOnly(tmpBundle)) {
        Manifest manifest = bundle.getManifest();
        Path evolutionPath = bundle.getPath(".ro/evolution.ttl");
        assertTrue("expected a history file", Files.exists(evolutionPath));
        assertEquals("expected exactly one history", 1, manifest.getHistory().size());
        Bundles.closeBundle(bundle);
    } catch (IOException e) {
        fail("failed to read bundle for history test: " + e.getMessage());
    }

    Files.delete(tmpBundle);
}

From source file:com.github.ffremont.microservices.springboot.manager.nexus.NexusClientApi.java

/**
 * Retourne la ressource//from   w w w.ja v  a 2  s  .  c  o  m
 *
 * @param groupId
 * @param artifact
 * @param classifier
 * @param version
 * @param packaging
 * @return
 */
public Path getBinary(String groupId, String artifact, String packaging, String classifier, String version) {
    String template = nexusProps.getBaseurl()
            + "/service/local/artifact/maven/redirect?r={r}&g={g}&a={a}&v={v}&p={p}", url;
    Path tempFileBinary = null;
    HttpURLConnection nexusConnexion;
    for (String repo : nexusProps.getRepo()) {
        url = template.replace("{r}", repo).replace("{g}", groupId).replace("{a}", artifact)
                .replace("{v}", version).replace("{p}", packaging);
        if (classifier != null) {
            url = url.concat("&c=" + classifier);
        }

        try {
            URL nexus = new URL(url);
            nexusConnexion = (HttpURLConnection) nexus.openConnection();
            nexusConnexion.connect();
            if (nexusConnexion.getResponseCode() != 200) {
                LOG.warn("Nexus : rcupration impossible pour le repo {}, statut {}", repo,
                        nexusConnexion.getResponseCode());
                continue;
            }
            tempFileBinary = Files.createTempFile("nexusBinary", "sbDeployer");
            FileOutputStream fos = new FileOutputStream(tempFileBinary.toFile());

            try (InputStream is = nexusConnexion.getInputStream()) {
                byte[] buffer = new byte[10240]; // 10ko
                int read;
                while (-1 != (read = is.read(buffer))) {
                    fos.write(buffer, 0, read);
                }
                fos.flush();
                is.close();

                break;
            }
        } catch (IOException ex) {
            LOG.debug("Une erreur  l'alimentation du fichier temporaire", ex);
            // si une exception se produit, je supp. le fichier temporaire
            if (tempFileBinary != null) {
                try {
                    Files.delete(tempFileBinary);
                } catch (IOException e) {
                }
            }
        }
    }

    return tempFileBinary;
}

From source file:de.hybris.platform.media.storage.impl.MediaCacheRecreatorTest.java

private void cleanCacheFolder(final String folderName) throws IOException {
    Files.walkFileTree(Paths.get(System.getProperty("java.io.tmpdir"), folderName),
            new SimpleFileVisitor<Path>() {
                @Override/*from   w ww .  ja  v  a  2s.c o m*/
                public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                        throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(final Path file, final IOException exc)
                        throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }
            });
}

From source file:ee.ria.xroad.common.conf.globalconf.GlobalConfTest.java

private static void deleteConfigurationFiles(Path confFiles) {
    try {/*  w w  w . ja va 2s.c  o  m*/
        Files.delete(confFiles);
    } catch (IOException e) {
        // Ignore.
    }
}

From source file:com.esri.geoportal.harvester.sink.SinkFile.java

/**
 * Attempts to delete file//from  w ww .j a va2 s. co m
 * @param attempts number of attempts
 * @param mills delay between consecutive attempts
 * @throws IOException if all attempts fail
 */
private void attemptToDeleteFile(int attempts, long mills) throws IOException {
    while (true) {
        attempts--;
        try {
            Files.delete(file);
            return;
        } catch (FileSystemException ex) {
            // if not check if maximum number of attempts has been exhausted...
            if (attempts <= 0) {
                // ...then throw exceptiion
                throw ex;
            }
            // otherwise wait and try again latter
            try {
                Thread.sleep(mills);
            } catch (InterruptedException e) {
                // ignore
            }
        }
    }
}