Example usage for java.nio.file Files deleteIfExists

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

Introduction

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

Prototype

public static boolean deleteIfExists(Path path) throws IOException 

Source Link

Document

Deletes a file if it exists.

Usage

From source file:org.digidoc4j.impl.bdoc.BDocContainerTest.java

@AfterClass
public static void deleteTemporaryFiles() {
    try {//from   w w  w  .  j a va 2  s  .  c o m
        DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get("."));
        for (Path item : directoryStream) {
            String fileName = item.getFileName().toString();
            if (fileName.endsWith("bdoc") && fileName.startsWith("test"))
                Files.deleteIfExists(item);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:nl.mpi.lamus.filesystem.implementation.LamusWorkspaceFileHandler.java

/**
 * @see WorkspaceFileHandler#deleteFile(java.io.File)
 *//*from   ww  w.j  av a2s.c o m*/
@Override
public void deleteFile(File file) throws IOException {

    Files.deleteIfExists(file.toPath());
}

From source file:org.sakuli.datamodel.helper.TestSuiteHelperTest.java

@Test
public void testModifyFiles() throws Exception {
    Path path = Paths.get("temp-testsuite.suite");
    try {/*from  w ww.java 2 s.c  o m*/
        String source = "line1\r\n\r\nbla\r\n";
        FileUtils.writeStringToFile(path.toFile(), source);
        FileTime beforeTimeStamp = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);
        Thread.sleep(1100);

        String result = TestSuiteHelper.prepareTestSuiteFile(path);
        assertEquals(result, "line1\r\n//\r\nbla\r\n");
        FileTime afterTimeStamp = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);
        assertNotEquals(beforeTimeStamp, afterTimeStamp);
    } finally {
        Files.deleteIfExists(path);
    }
}

From source file:com.vaushell.superpipes.transforms.done.T_DoneTest.java

/**
 * Test duplicate with fields./* ww w . j av  a2  s .co m*/
 *
 * @throws java.lang.Exception
 */
@Test
public void testDuplicate2() throws Exception {
    final A_Node n = dispatcher.addNode("dummy2", N_Dummy.class, ConfigProperties.EMPTY_COMMONS);
    final A_Transform t = n.addTransformIN(T_Done.class, Arrays.asList(dispatcher.getCommon("id")));

    final Path p = dispatcher.getDatas().resolve(Paths.get(n.getNodeID(), "done.dat"));

    Files.deleteIfExists(p);

    // Prepare
    n.prepare();

    // Transform
    final Message mLearn = Message.create(Message.KeyIndex.TITLE, "mon titre", Message.KeyIndex.DESCRIPTION,
            "ma description");
    final Message mLearn2 = Message.create(Message.KeyIndex.TITLE, "mon titre", Message.KeyIndex.DESCRIPTION,
            "ma description2");

    assertNotNull("Message is learned", t.transform(mLearn));
    assertNull("Message 2 is not learned", t.transform(mLearn2));

    // Terminate
    n.terminate();
}

From source file:org.fao.geonet.services.logo.Set.java

public Element exec(Element params, ServiceContext context) throws Exception {

    Path harvestingLogoDirectory = Resources.locateHarvesterLogosDir(context);
    Path nodeLogoDirectory = Resources.locateLogosDir(context);

    String file = Util.getParam(params, Params.FNAME);
    String asFavicon = Util.getParam(params, Params.FAVICON, "0");

    FilePathChecker.verify(file);//from   ww  w  .  j av  a2s  .  c  o  m

    if (StringUtils.isEmpty(file)) {
        throw new Exception("Logo name is not defined.");
    }

    SettingManager settingMan = context.getBean(SettingManager.class);
    String nodeUuid = settingMan.getSiteId();

    try {
        Path logoFilePath = harvestingLogoDirectory.resolve(file);
        if (!Files.exists(logoFilePath)) {
            logoFilePath = context.getAppPath().resolve("images/harvesting/" + file);
        }
        try (InputStream inputStream = Files.newInputStream(logoFilePath)) {
            BufferedImage source = ImageIO.read(inputStream);

            if ("1".equals(asFavicon)) {
                createFavicon(source, nodeLogoDirectory.resolve("favicon.png"));
            } else {
                Path logo = nodeLogoDirectory.resolve(nodeUuid + ".png");
                Path defaultLogo = nodeLogoDirectory.resolve("logo.png");

                if (!file.endsWith(".png")) {
                    try (OutputStream logoOut = Files.newOutputStream(logo);
                            OutputStream defLogoOut = Files.newOutputStream(defaultLogo);) {
                        ImageIO.write(source, "png", logoOut);
                        ImageIO.write(source, "png", defLogoOut);
                    }
                } else {
                    Files.deleteIfExists(logo);
                    IO.copyDirectoryOrFile(logoFilePath, logo, false);
                    Files.deleteIfExists(defaultLogo);
                    IO.copyDirectoryOrFile(logoFilePath, defaultLogo, false);
                }
            }
        }
    } catch (Exception e) {
        throw new Exception(
                "Unable to move uploaded thumbnail to destination directory. Error: " + e.getMessage());
    }

    Element response = new Element("response");
    response.addContent(new Element("status").setText("Logo set."));
    return response;
}

From source file:org.ng200.openolympus.FileAccess.java

public static void deleteDirectoryByWalking(final Path path) throws IOException {
    if (!Files.exists(path)) {
        return;/*  w  w  w. jav a  2 s  .  c  o  m*/
    }
    FileAccess.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult postVisitDirectory(final Path dir, final IOException e) throws IOException {
            if (e == null) {
                FileAccess.delete(dir);
                return FileVisitResult.CONTINUE;
            } else {
                throw e;
            }
        }

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

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

From source file:org.apache.storm.localizer.LocalizedResource.java

static void completelyRemoveUnusedUser(Path localBaseDir, String user) throws IOException {
    Path userFileCacheDir = getLocalUserFileCacheDir(localBaseDir, user);
    // baseDir/supervisor/usercache/user1/filecache/files
    Files.deleteIfExists(getCacheDirForFiles(userFileCacheDir));
    // baseDir/supervisor/usercache/user1/filecache/archives
    Files.deleteIfExists(getCacheDirForArchives(userFileCacheDir));
    // baseDir/supervisor/usercache/user1/filecache
    Files.deleteIfExists(userFileCacheDir);
    // baseDir/supervisor/usercache/user1
    Files.deleteIfExists(getLocalUserDir(localBaseDir, user));
}

From source file:org.ballerinalang.stdlib.system.FileSystemTest.java

@Test(description = "Test for changing file path")
public void testFileRename() throws IOException {
    try {//ww  w. j  a v a  2 s. co m
        Files.copy(srcFilePath, tempSourcePath, StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES);

        BValue[] args = { new BString(tempSourcePath.toString()), new BString(tempDestPath.toString()) };
        BRunUtil.invoke(compileResult, "testRename", args);
        Assert.assertTrue(Files.exists(tempDestPath));
        assertFalse(Files.exists(tempSourcePath));
    } finally {
        Files.deleteIfExists(tempSourcePath);
        Files.deleteIfExists(tempDestPath);
    }
}

From source file:org.jboss.as.test.integration.logging.formatters.JsonFormatterTestCase.java

@After
public void remove() throws Exception {

    final CompositeOperationBuilder builder = CompositeOperationBuilder.create();

    // Remove the logger
    builder.addStep(Operations.createRemoveOperation(LOGGER_ADDRESS));

    // Remove the formatter
    builder.addStep(Operations.createRemoveOperation(FORMATTER_ADDRESS));

    // Remove the custom handler
    builder.addStep(Operations.createRemoveOperation(HANDLER_ADDRESS));

    executeOperation(builder.build());/*from  w  w  w. j  a  va 2s.  c o  m*/

    if (logFile != null)
        Files.deleteIfExists(logFile);
}

From source file:io.redlink.solrlib.standalone.SolrServerConnector.java

@Override
@SuppressWarnings("squid:S3776")
protected void init(ExecutorService executorService) throws IOException, SolrServerException {
    Preconditions.checkState(initialized.compareAndSet(false, true));
    Preconditions.checkArgument(Objects.nonNull(solrBaseUrl));

    if (configuration.isDeployCores() && Objects.nonNull(configuration.getSolrHome())) {
        final Path solrHome = configuration.getSolrHome();
        Files.createDirectories(solrHome);
        final Path libDir = solrHome.resolve("lib");
        Files.createDirectories(libDir);

        try (HttpSolrClient solrClient = new HttpSolrClient.Builder(solrBaseUrl).build()) {
            for (SolrCoreDescriptor coreDescriptor : coreDescriptors) {
                final String coreName = coreDescriptor.getCoreName();
                if (availableCores.containsKey(coreName)) {
                    log.warn("CoreName-Clash: {} already initialized. Skipping {}", coreName,
                            coreDescriptor.getClass());
                    continue;
                }/*from  w ww.  j a v a 2s .  c om*/
                final String remoteName = createRemoteName(coreName);

                final Path coreHome = solrHome.resolve(remoteName);
                coreDescriptor.initCoreDirectory(coreHome, libDir);

                final Path corePropertiesFile = coreHome.resolve("core.properties");
                // core.properties is created by the CreateCore-Command.
                Files.deleteIfExists(corePropertiesFile);

                if (coreDescriptor.getNumShards() > 1 || coreDescriptor.getReplicationFactor() > 1) {
                    log.warn("Deploying {} to SolrServerConnector, ignoring config of shards={},replication={}",
                            coreName, coreDescriptor.getNumShards(), coreDescriptor.getReplicationFactor());
                }

                // Create or reload the core
                if (CoreAdminRequest.getStatus(remoteName, solrClient).getStartTime(remoteName) == null) {
                    final CoreAdminResponse adminResponse = CoreAdminRequest.createCore(remoteName,
                            coreHome.toAbsolutePath().toString(), solrClient);
                } else {
                    final CoreAdminResponse adminResponse = CoreAdminRequest.reloadCore(remoteName, solrClient);
                }
                // schedule client-side core init
                final boolean isNewCore = findInNamedList(
                        CoreAdminRequest.getStatus(remoteName, solrClient).getCoreStatus(remoteName), "index",
                        "lastModified") == null;
                scheduleCoreInit(executorService, coreDescriptor, isNewCore);

                availableCores.put(coreName, coreDescriptor);
            }
        }
    } else {
        try (HttpSolrClient solrClient = new HttpSolrClient.Builder(solrBaseUrl).build()) {
            for (SolrCoreDescriptor coreDescriptor : coreDescriptors) {
                final String coreName = coreDescriptor.getCoreName();
                if (availableCores.containsKey(coreName)) {
                    log.warn("CoreName-Clash: {} already initialized. Skipping {}", coreName,
                            coreDescriptor.getClass());
                    continue;
                }
                final String remoteName = createRemoteName(coreName);
                if (CoreAdminRequest.getStatus(remoteName, solrClient).getStartTime(remoteName) == null) {
                    // Core does not exists
                    log.warn("Collection {} (remote: {}) not available in Solr '{}' "
                            + "but deployCores is set to false", coreName, remoteName, solrBaseUrl);
                } else {
                    log.debug("Collection {} exists in Solr '{}' as {}", coreName, solrBaseUrl, remoteName);
                    scheduleCoreInit(executorService, coreDescriptor, false);
                    availableCores.put(coreName, coreDescriptor);
                }
            }
        }
    }
}