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.jboss.as.test.manualmode.logging.LoggingPreferencesTestCase.java

private void clearLogFiles() throws IOException {
    Files.deleteIfExists(profileLog);
    Files.deleteIfExists(perDeployLog);
}

From source file:org.nuxeo.ecm.core.api.impl.blob.FileBlob.java

/**
 * Moves this blob's temporary file to a new non-temporary location.
 * <p>/*from w w w.  ja v a2s. c  o  m*/
 * The move is done as atomically as possible.
 *
 * @since 7.2
 */
public void moveTo(File dest) throws IOException {
    if (!isTemporary) {
        throw new IOException("Cannot move non-temporary file: " + file);
    }
    Path path = file.toPath();
    Path destPath = dest.toPath();
    try {
        Files.move(path, destPath, ATOMIC_MOVE);
        file = dest;
    } catch (AtomicMoveNotSupportedException e) {
        // Do a copy through a tmp file on the same filesystem then atomic rename
        Path tmp = Files.createTempFile(destPath.getParent(), null, null);
        try {
            Files.copy(path, tmp, REPLACE_EXISTING);
            Files.delete(path);
            Files.move(tmp, destPath, ATOMIC_MOVE);
            file = dest;
        } catch (IOException ioe) {
            // don't leave tmp file in case of error
            Files.deleteIfExists(tmp);
            throw ioe;
        }
    }
    isTemporary = false;
}

From source file:nl.mpi.lamus.workspace.exporting.implementation.LamusVersioningHandler.java

/**
 * @see VersioningHandler#moveOrCopyFileToOrphansFolder(nl.mpi.lamus.workspace.model.Workspace, nl.mpi.lamus.workspace.model.WorkspaceNode)
 *//*w w w .j  av  a2  s.  co  m*/
@Override
public URL moveOrCopyFileToOrphansFolder(Workspace workspace, WorkspaceNode nodeToMove, boolean copy) {

    File orphanOldLocation = null;

    File archiveLocation = null;

    //if file was not in the archive already, then it will be moved from its workspace location
    //if file is in the archive and is a resource, then it will be moved from its archive location
    //if file is metadata, then it will be moved from its workspace location; if it is also in the archive, then it has to be removed from there

    if (nodeToMove.getArchiveURI() != null) {
        CorpusNode archiveNode = corpusStructureProvider.getNode(nodeToMove.getArchiveURI());
        archiveLocation = nodeResolver.getLocalFile(archiveNode);
    }

    if (nodeToMove.getArchiveURI() == null || nodeUtil.isNodeMetadata(nodeToMove)) {
        URL orphanOldLocationUrl = nodeToMove.getWorkspaceURL();
        orphanOldLocation = new File(orphanOldLocationUrl.getPath());
        if (archiveFileLocationProvider.isFileInOrphansDirectory(orphanOldLocation)) {
            logger.info("File already in orphans directory: " + orphanOldLocation.getAbsolutePath());
            return orphanOldLocationUrl;
        }
    }

    if (orphanOldLocation == null) {
        orphanOldLocation = archiveLocation;
    }

    String filename;
    if (orphanOldLocation != null) {
        filename = orphanOldLocation.getName();
    } else {
        throw new IllegalStateException("No valid file location was found.");
    }

    File orphanNewLocation;
    try {
        File orphansDirectory = archiveFileLocationProvider
                .getOrphansDirectory(workspace.getTopNodeArchiveURL().toURI());
        if (!archiveFileHelper.canWriteTargetDirectory(orphansDirectory)) {
            logger.error("Problem with write permissions in target directory " + orphansDirectory);
            return null;
        }
        orphanNewLocation = archiveFileHelper.getFinalFile(orphansDirectory, filename);
    } catch (URISyntaxException ex) {
        String errorMessage = "Error retrieving archive location of node " + workspace.getTopNodeArchiveURI();
        logger.error(errorMessage, ex);
        return null;
    }

    try {
        if (!copy) {
            FileUtils.moveFile(orphanOldLocation, orphanNewLocation);
            if (archiveLocation != null) {
                Files.deleteIfExists(archiveLocation.toPath());
            }
        } else {
            FileUtils.copyFile(orphanOldLocation, orphanNewLocation);
        }

    } catch (IOException ex) {
        logger.error("File couldn't be " + (copy ? "copied" : "moved") + " from [" + orphanOldLocation
                + "] to [" + orphanNewLocation + "]", ex);
        return null;
    }

    URL newFileUrl = null;
    try {
        newFileUrl = orphanNewLocation.toURI().toURL();
    } catch (MalformedURLException ex) {
        logger.warn((copy ? "Copied" : "Moved") + " file location is not a URL", ex);
    }

    return newFileUrl;
}

From source file:org.egov.infra.filestore.service.impl.LocalDiskFileStoreServiceTest.java

@Test
public final void testUploadSetOfFile() throws IOException {
    Set<File> files = new HashSet<>();
    for (int no = 0; no < 10; no++) {
        final File newFile = Files.createTempFile(tempFilePath, "xyz" + no, "txt").toFile();
        FileUtils.write(newFile, "Test", UTF_8);
        files.add(newFile);/* ww  w. j av  a 2s .  com*/
    }
    for (File file : files) {
        Files.deleteIfExists(file.toPath());
    }
}

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

@Test(description = "Test for removing file/directory from system")
public void testFileRemove() throws IOException {
    Path tempSourceDirPath = null;
    try {//from ww  w  .j  a  v a 2 s .  c om
        tempSourceDirPath = tempDirPath.resolve("src-dir");
        FileUtils.copyDirectory(srcDirPath.toFile(), tempSourceDirPath.toFile());
        Files.copy(srcFilePath, tempSourcePath, StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES);
        // Remove source file
        BValue[] args = { new BString(tempSourcePath.toString()), new BBoolean(false) };
        BRunUtil.invoke(compileResult, "testRemove", args);
        assertFalse(Files.exists(tempSourcePath));

        // Remove directory with recursive false
        BValue[] args1 = { new BString(tempSourceDirPath.toString()), new BBoolean(false) };
        BValue[] returns = BRunUtil.invoke(compileResult, "testRemove", args1);
        assertTrue(returns[0] instanceof BError);
        BError error = (BError) returns[0];
        assertEquals(error.getReason(), "{ballerina/system}OPERATION_FAILED");
        log.info("Ballerina error: " + error.getDetails().stringValue());

        // Remove directory with recursive true
        BValue[] args2 = { new BString(tempSourceDirPath.toString()), new BBoolean(true) };
        returns = BRunUtil.invoke(compileResult, "testRemove", args2);
        assertNull(returns[0]);
        assertFalse(Files.exists(tempSourceDirPath));

    } finally {
        Files.deleteIfExists(tempSourcePath);
        if (tempSourceDirPath != null) {
            FileUtils.deleteDirectory(tempSourceDirPath.toFile());
        }
    }
}

From source file:modmanager.backend.ModificationOption.java

/**
 * Uninstalls given source file//from w w w  . ja v a 2 s . co  m
 *
 * @param file
 */
protected void uninstall(File file) {
    logger.log(Level.INFO, "Uninstalling {0} ...", file.getAbsolutePath());

    File destination = getDestinationFile(file);

    try {
        Files.deleteIfExists(destination.toPath());
    } catch (IOException ex) {
        logger.log(Level.WARNING, "Could not uninstall because of: {0}", ex.getMessage());
    }
}

From source file:org.digidoc4j.main.DigiDoc4JTest.java

@Test
public void createsECCSignature() throws Exception {
    String fileName = "createsECCSignature.bdoc";
    Files.deleteIfExists(Paths.get(fileName));

    String[] params = new String[] { "-in", fileName, "-add", "testFiles/test.txt", "text/plain", "-pkcs12",
            "testFiles/ec-digiid.p12", "inno", "-e", "ECDSA" };

    System.setProperty("digidoc4j.mode", "TEST");
    callMainWithoutSystemExit(params);/*from w w w.j av  a2 s. c  o m*/

    Container container = ContainerOpener.open(fileName);
    assertTrue(container.validate().isValid());
}

From source file:org.codice.ddf.admin.insecure.defaults.service.DefaultUsersDeletionScheduler.java

public void deleteScheduledDeletions() {
    try {//from   w w  w .  ja  v a 2 s .c  o m
        if (context.getRoute(ROUTE_ID) != null && context.getRouteStatus(ROUTE_ID).isStarted()
                && context.getRouteStatus(ROUTE_ID).isStoppable()) {
            context.stopRoute(ROUTE_ID);
            Files.deleteIfExists(getTempTimestampFilePath());
            LOGGER.debug("The deletion of default users has been stopped successfully.");
        }
    } catch (Exception e) {
        LOGGER.debug("Unable to stop deletion.", e);
    }
}

From source file:ch.cyberduck.core.Local.java

/**
 * Delete the file//from ww w . ja  v a  2s  . c  om
 */
public void delete() throws AccessDeniedException {
    try {
        Files.deleteIfExists(Paths.get(path));
    } catch (IOException e) {
        throw new LocalAccessDeniedException(String.format("Delete %s failed", path), e);
    }
}

From source file:com.netflix.genie.web.services.impl.DiskJobFileServiceImpl.java

/**
 * {@inheritDoc}//from w ww .j ava 2  s.c  o  m
 */
@Override
public void deleteJobFile(final String jobId, final String relativePath) throws IOException {
    log.debug("Requested to delete file {} for job {}", relativePath, jobId);
    final Path jobFile = this.jobsDirRoot.resolve(jobId).resolve(relativePath);

    if (Files.deleteIfExists(jobFile)) {
        log.debug("Deleted file {} for job {}", relativePath, jobId);
    } else {
        log.debug("No file {} exists for job {}. Ignoring", relativePath, jobId);
    }
}