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:io.lavagna.service.ExportImportServiceTest.java

@Test
public void testImportAndExport() throws IOException {
    Path tmp = Files.createTempFile(null, null);
    try (InputStream is = new ClassPathResource("io/lavagna/export2.zip").getInputStream()) {
        Files.copy(is, tmp, StandardCopyOption.REPLACE_EXISTING);
        exportImportService.importData(false, tmp);

        // TODO additional checks

        exportImportService.exportData(new ByteArrayOutputStream());
    } finally {//from  ww w .ja v  a2s.  c o  m
        if (tmp != null) {
            Files.deleteIfExists(tmp);
        }
    }

}

From source file:ch.ledcom.jpreseed.web.TemporaryPreseedStore.java

private void deletePreseeds() {
    for (Path preseed : preseedPaths) {
        try {/*from ww w  .j av  a2s.  c om*/
            logger.debug("Deleting preseed file [{}].", preseed);
            Files.deleteIfExists(preseed);
        } catch (IOException ioe) {
            logger.error("Could not delete preseed file", ioe);
        }
    }
}

From source file:org.apache.archiva.consumers.core.ArtifactMissingChecksumsConsumerTest.java

@Test
public void testNoExistingChecksums() throws Exception {
    String path = "/no-checksums-artifact/1.0/no-checksums-artifact-1.0.jar";

    Path sha1Path = Paths.get(repoConfig.getLocation(), path + ".sha1");
    Path md5FilePath = Paths.get(repoConfig.getLocation(), path + ".md5");

    Files.deleteIfExists(sha1Path);
    Files.deleteIfExists(md5FilePath);

    Assertions.assertThat(sha1Path.toFile()).doesNotExist();
    Assertions.assertThat(md5FilePath.toFile()).doesNotExist();

    consumer.beginScan(repoConfig, Calendar.getInstance().getTime());

    consumer.processFile(path);/*from   w ww.j  a va2 s .  c o m*/

    Assertions.assertThat(sha1Path.toFile()).exists();
    long sha1LastModified = sha1Path.toFile().lastModified();
    Assertions.assertThat(md5FilePath.toFile()).exists();
    long md5LastModified = md5FilePath.toFile().lastModified();
    Thread.sleep(1000);
    consumer.processFile(path);

    Assertions.assertThat(sha1Path.toFile()).exists();
    Assertions.assertThat(md5FilePath.toFile()).exists();

    Assertions.assertThat(sha1Path.toFile().lastModified()).isEqualTo(sha1LastModified);

    Assertions.assertThat(md5FilePath.toFile().lastModified()).isEqualTo(md5LastModified);
}

From source file:org.aspache.tamaya.examples.fileobserver.ObservedConfigExampleTest.java

@AfterClass
public static void cleanup() throws Exception {
    // cleanup directory
    Files.deleteIfExists(getTargetFile("test1.properties"));
    Files.deleteIfExists(getTargetFile("test2.properties"));
    Files.deleteIfExists(getTargetFile("test3.properties"));
}

From source file:com.github.horrorho.inflatabledonkey.cache.FileCache.java

public boolean remove(Path file) throws IOException {
    boolean isDeleted = Files.deleteIfExists(file);
    logger.debug("-- remove() - file: {} deleted: {}", file, isDeleted);
    return isDeleted;
}

From source file:eu.europa.ec.markt.dss.signature.StreamDocumentTest.java

@Test
public void save() throws Exception {
    document.save("streamDocumentSaveTest.txt");
    assertTrue(Files.exists(Paths.get("streamDocumentSaveTest.txt")));

    FileReader fileReader = new FileReader("streamDocumentSaveTest.txt");
    int read = fileReader.read();
    fileReader.close();//from w w  w .  j  a  v  a  2s.c o  m

    assertEquals(65, read);
    Files.deleteIfExists(Paths.get("streamDocumentSaveTest.txt"));
}

From source file:org.jboss.as.test.manualmode.elytron.CustomCredentialSecurityFactoryTestCase.java

public static void prepareServerConfiguration() throws Exception {
    tempFolder = Files/*from  ww  w  . j a v  a2  s .  co  m*/
            .createTempDirectory("ely-" + CustomCredentialSecurityFactoryTestCase.class.getSimpleName());

    Path fsRealmPath = tempFolder.resolve("fs-realm-users");

    try (CLIWrapper cli = new CLIWrapper(true)) {
        final String levelStr = "";

        Path moduleJar = createJar("testJar", CustomCredentialSecurityFactoryImpl.class);
        try {
            cli.sendLine("module add --name=" + CUSTOM_CREDENTIAL_SECURITY_FACTORY_MODULE_NAME
                    + " --slot=main --dependencies=org.wildfly.security.elytron,org.wildfly.extension.elytron --resources="
                    + moduleJar.toAbsolutePath());
        } finally {
            Files.deleteIfExists(moduleJar);
        }

        cli.sendLine(String.format(
                "/subsystem=elytron/custom-credential-security-factory=%s:add(class-name=%s, module=%s)",
                CUSTOM_CRED_SEC_FACTORY_NAME, CustomCredentialSecurityFactoryImpl.class.getName(),
                CUSTOM_CREDENTIAL_SECURITY_FACTORY_MODULE_NAME));

        cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add(path=\"%s\", %s)",
                MANAGEMENT_FILESYSTEM_NAME, escapePath(fsRealmPath.toAbsolutePath().toString()), levelStr));
        cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add-identity(identity=%s)",
                MANAGEMENT_FILESYSTEM_NAME, USER));
        cli.sendLine(String.format(
                "/subsystem=elytron/filesystem-realm=%s:set-password(identity=%s, clear={password=\"%s\"})",
                MANAGEMENT_FILESYSTEM_NAME, USER, CORRECT_PASSWORD));

        cli.sendLine(String.format(
                "/subsystem=elytron/security-domain=%1$s:add(realms=[{realm=%1$s,role-decoder=groups-to-roles},{realm=local,role-mapper=super-user-mapper}],default-realm=%1$s,permission-mapper=default-permission-mapper)",
                MANAGEMENT_FILESYSTEM_NAME));
        cli.sendLine(String.format(
                "/subsystem=elytron/http-authentication-factory=%1$s:add(http-server-mechanism-factory=%2$s,security-domain=%1$s,"
                        + "mechanism-configurations=[{mechanism-name=BASIC,mechanism-realm-configurations=[{realm-name=\"%1$s\"}]}, credential-security-factory=%3$s])",
                MANAGEMENT_FILESYSTEM_NAME, PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY,
                CUSTOM_CRED_SEC_FACTORY_NAME));
        cli.sendLine(String.format(
                "/core-service=management/management-interface=http-interface:write-attribute(name=http-authentication-factory,value=%s)",
                MANAGEMENT_FILESYSTEM_NAME));
        ServerReload.executeReloadAndWaitForCompletion(CONTROLLER.getClient().getControllerClient());
    }
}

From source file:org.sakuli.services.common.LogCleanUpResultServiceImpl.java

/**
 * Cleans the {@link Path} from files, which are older then {@link SakuliProperties#logMaxAge}.
 * On error no exception will be thrown, du to the facts, that`s only a optional cleanup.
 *
 * @param path root folder of files to clean
 *///from w w w  .  ja  v  a  2s  .c  o m
void cleanUpDirectory(Path path) {
    try {
        Instant maxDate = Instant.now().minus(sakuliProperties.getLogMaxAge(), ChronoUnit.DAYS);
        Files.newDirectoryStream(path).forEach(e -> {
            if (Files.isDirectory(e)) {
                cleanUpDirectory(e);
            } else if (Files.isRegularFile(e)) {
                try {
                    if (Files.getLastModifiedTime(e).toInstant().isBefore(maxDate)) {
                        LOGGER.info("cleanup to old log file '{}'", e);
                        Files.deleteIfExists(e);
                    }
                } catch (IOException e1) {
                    LOGGER.error("can`t delete file", e1);
                }
            }
        });
    } catch (IOException e) {
        LOGGER.error("couldn`t access log file directory '" + path + "'", e);
    }
}

From source file:org.apache.tika.cli.TikaCLIBatchCommandLineTest.java

@After
public void tearDown() {
    try {//from   w w w .ja  va2 s.  c  o  m
        //TODO: refactor this to use our FileUtils.deleteDirectory(Path)
        //when that is ready
        FileUtils.deleteDirectory(testInput.toFile());
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            Files.deleteIfExists(testFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}