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.codice.ddf.catalog.plugin.metacard.backup.storage.filestorage.MetacardFileStorageRoute.java

public static void deleteFile(String startingDir, String fileName) {

    String fullFilePath = null;// w w w.j ava  2 s  .  c om
    try {
        fullFilePath = String.format("%s%s%s", URLDecoder.decode(startingDir, StandardCharsets.UTF_8.name()),
                File.separator, URLDecoder.decode(fileName, StandardCharsets.UTF_8.name()));
        Files.deleteIfExists(Paths.get(fullFilePath));
        LOGGER.trace("Deleted File : {}", fullFilePath);
    } catch (IOException e) {
        LOGGER.debug("Could not delete file at path : {}", fullFilePath, e);
    }
}

From source file:mpimp.assemblxweb.util.J5FileUtils.java

public static void deleteTuSubunitRelatedFiles(TuSubunit tuSubunit, AssemblXWebModel model) throws IOException {
    if (tuSubunit.getSequenceFileLoaded()) {
        // check first if the sequence file is not used by another subunit
        // as well
        List<TuSubunit> tuSubunits = tuSubunit.getParentTuUnit().getTuSubunits();
        int counter = 0;
        for (TuSubunit currentTuSubunit : tuSubunits) {
            if (currentTuSubunit.getSequenceFileName() != null
                    && currentTuSubunit.getSequenceFileName().equals(tuSubunit.getSequenceFileName())) {
                counter++;//from w w w .  j a  v a 2  s  .  c o  m
            }
        }
        if (counter > 1) {
            return; // sequence file is used more than once, so we must
                    // not delete it along with the subunit
        }
        String sequenceFilePathName = model.getWorkingDirectory() + File.separator
                + model.getCurrentTuUnit().getTuDirectoryName() + File.separator
                + AssemblXWebProperties.getInstance().getProperty("sequenceFileDirectory") + File.separator
                + tuSubunit.getSequenceFileName();
        Files.deleteIfExists(Paths.get(sequenceFilePathName));
        String sequencesDirPath = model.getWorkingDirectory() + File.separator
                + model.getCurrentTuUnit().getTuDirectoryName() + File.separator
                + AssemblXWebProperties.getInstance().getProperty("sequenceFileDirectory");
        File sequencesDir = new File(sequencesDirPath);
        if (sequencesDir.isDirectory() && sequencesDir.list().length == 0) {
            Files.delete(Paths.get(sequencesDirPath));
        }
        String tuDirectoryPath = model.getWorkingDirectory() + File.separator
                + model.getCurrentTuUnit().getTuDirectoryName();
        File tuDirectory = new File(tuDirectoryPath);
        if (tuDirectory.isDirectory() && tuDirectory.list().length == 0) {
            Files.delete(Paths.get(tuDirectoryPath));
        }
    }
}

From source file:org.jboss.as.test.manualmode.logging.Log4jAppenderTestCase.java

@After
public void stopContainer() throws Exception {
    // Remove the servlet
    undeploy();//from  ww  w.jav a  2 s.  c om

    final CompositeOperationBuilder builder = CompositeOperationBuilder.create();
    // Remove the handler from the root-logger
    ModelNode op = Operations.createOperation("remove-handler", ROOT_LOGGER_ADDRESS);
    op.get(ModelDescriptionConstants.NAME).set(CUSTOM_HANDLER_NAME);
    builder.addStep(op);

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

    executeOperation(builder.build());

    Files.deleteIfExists(logFile);

    // Stop the container
    container.stop();
}

From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java

@Test
public void testRelativeSymlink() throws IOException, URISyntaxException {
    assumeFalse(Platform.isWindows());//from  ww  w.jav  a2  s.  com
    final Path tempDir = Files.createTempDirectory("ds3_file_object_rel_test_");
    final Path tempPath = Files.createTempFile(tempDir, "temp_", ".txt");

    try {
        try (final SeekableByteChannel channel = Files.newByteChannel(tempPath, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(testData));
        }

        final Path symLinkPath = tempDir.resolve("sym_" + tempPath.getFileName().toString());
        final Path relPath = Paths.get("..", getParentDir(tempPath), tempPath.getFileName().toString());

        LOG.info("Creating symlink from " + symLinkPath.toString() + " to " + relPath.toString());

        Files.createSymbolicLink(symLinkPath, relPath);
        getFileWithPutter(tempDir, symLinkPath);

    } finally {
        Files.deleteIfExists(tempPath);
        Files.deleteIfExists(tempDir);
    }
}

From source file:com.liferay.sync.engine.SyncSystemTest.java

protected static void cleanUp(long delay) throws Exception {
    for (long syncAccountId : _syncAccountIds.values()) {
        SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(syncAccountId);

        if (syncAccount == null) {
            return;
        }/*from ww w  .  j  a v a  2s . c om*/

        Files.walkFileTree(Paths.get(syncAccount.getFilePathName()), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult postVisitDirectory(Path filePath, IOException ioe) throws IOException {

                Files.deleteIfExists(filePath);

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path filePath, BasicFileAttributes basicFileAttributes)
                    throws IOException {

                Files.deleteIfExists(filePath);

                return FileVisitResult.CONTINUE;
            }

        });
    }

    pause(delay);

    SyncEngine.stop();

    Files.walkFileTree(Paths.get(_rootFilePathName), new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult postVisitDirectory(Path filePath, IOException ioe) throws IOException {

            Files.delete(filePath);

            return FileVisitResult.CONTINUE;
        }

    });

    for (long syncAccountId : _syncAccountIds.values()) {
        SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(syncAccountId);

        SyncSystemTestUtil.deleteUser(syncAccount.getUserId(), _syncAccount.getSyncAccountId());

        SyncAccountService.deleteSyncAccount(syncAccountId);
    }

    SyncAccountService.deleteSyncAccount(_syncAccount.getSyncAccountId());
}

From source file:org.jboss.as.test.integration.logging.handlers.SocketHandlerTestCase.java

@AfterClass
public static void tearDown() throws Exception {
    undeploy(DEPLOYMENT_NAME);//ww  w  . j av a2  s .  c o  m
    // Clear the temporary directory and delete it
    Files.walkFileTree(TEMP_DIR, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }
    });
    Files.deleteIfExists(TEMP_DIR);
}

From source file:ch.bender.evacuate.EvacuateMainTest.java

/**
 * This method is executed just before each test method
 * //w  ww  .ja v  a  2  s  .  c  om
 * @throws Throwable
 *         On any problem (test method will not be executed)
 */
@Before
public void setUp() throws Throwable {
    myLog.debug("entering");
    try {
        if (Files.exists(Testconstants.ROOT_DIR)) {
            Helper.deleteDirRecursive(Testconstants.ROOT_DIR);
        }

        Files.createDirectory(Testconstants.ROOT_DIR);
        FSOBJECTS.DIR1.setFsObject(Testconstants.createNewFolder(Testconstants.ROOT_DIR, "existingDir1"));
        FSOBJECTS.DIR2.setFsObject(Testconstants.createNewFolder(Testconstants.ROOT_DIR, "existingDir2"));
        FSOBJECTS.DIR3.setFsObject(Testconstants.createNewFolder(Testconstants.ROOT_DIR, "existingDir3"));
        FSOBJECTS.FILE1.setFsObject(Testconstants.createNewFile(Testconstants.ROOT_DIR, "existingFile1.txt"));
        FSOBJECTS.FILE2.setFsObject(Testconstants.createNewFile(Testconstants.ROOT_DIR, "existingFile2.txt"));
        FSOBJECTS.FILE3.setFsObject(Testconstants.createNewFile(Testconstants.ROOT_DIR, "existingFile3.txt"));
        FSOBJECTS.NOT1.setFsObject(Paths.get(Testconstants.ROOT_DIR.toString(), "notExisting1"));
        FSOBJECTS.NOT2.setFsObject(Paths.get(Testconstants.ROOT_DIR.toString(), "notExisting2"));
        FSOBJECTS.NOT3.setFsObject(Paths.get(Testconstants.ROOT_DIR.toString(), "notExisting3"));

        Files.deleteIfExists(Paths.get(EXCLUDE_FILE_NAME));
        myExcludeFile = Testconstants.createNewFile(Paths.get("."), EXCLUDE_FILE_NAME);
        FileUtils.writeLines(myExcludeFile.toFile(), Arrays.asList(new String[] { EXCLUDE_VALUE }));
    } catch (Throwable t) {
        myLog.error("Throwable caught in setup", t);
        throw t;
    }
}

From source file:org.kitodo.dataeditor.MetsKitodoWriterTest.java

@Test
public void shouldWriteMetsFileFromOldFormat()
        throws TransformerException, JAXBException, IOException, DatatypeConfigurationException {
    URI xmlFile = Paths.get("./src/test/resources/testmetaOldFormat.xml").toUri();

    URI xmlTestFile = Paths.get(System.getProperty("user.dir") + "/target/test-classes/newtestmetaold.xml")
            .toUri();//from  ww  w. j a  va 2s  .c o  m

    MetsKitodoWrapper metsKitodoWrapper = new MetsKitodoWrapper(xmlFile, xsltFile);
    metsKitodoWriter.writeSerializedToFile(metsKitodoWrapper.getMets(), xmlTestFile);
    MetsKitodoWrapper savedMetsKitodoWrapper = new MetsKitodoWrapper(xmlTestFile, xsltFile);
    Files.deleteIfExists(Paths.get(xmlTestFile));

    String loadedMetadata = metsKitodoWrapper.getDmdSecs().get(0).getKitodoType().getMetadata().get(0)
            .getValue();
    String savedMetadata = savedMetsKitodoWrapper.getDmdSecs().get(0).getKitodoType().getMetadata().get(0)
            .getValue();

    Assert.assertEquals("The metadata of the loaded and the saved mets file are not equal", loadedMetadata,
            savedMetadata);
    Assert.assertEquals("The number of dmdSec elements of the loaded and the saved mets file are not equal",
            metsKitodoWrapper.getDmdSecs().size(), savedMetsKitodoWrapper.getDmdSecs().size());

    Assert.assertEquals("Conversation note was not inserted to mets header", 2,
            metsKitodoWrapper.getMets().getMetsHdr().getAgent().get(0).getNote().size());
}

From source file:rapture.blob.file.FileBlobStore.java

private Boolean createSymLink(String fromDisplayName, String toFilePath) {
    try {//from w w  w  . ja v a2s. c  o  m
        File fromFile = FileRepoUtils.makeGenericFile(parentDir, fromDisplayName + Parser.COLON_CHAR);
        Path fromFilePath = Paths.get(fromFile.getAbsolutePath());
        Files.deleteIfExists(fromFilePath);
        FileUtils.forceMkdir(fromFilePath.getParent().toFile());
        Files.createSymbolicLink(fromFilePath, Paths.get(toFilePath + Parser.COLON_CHAR));
    } catch (IOException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Fail to read blob content",
                e);
    }
    return true;
}

From source file:org.red5.server.service.ShutdownServer.java

/**
 * Starts internal server listening for shutdown requests.
 *///from  w  w  w.  j a  v a2  s .  c o  m
public void start() {
    // dump to stdout
    System.out.printf("Token: %s%n", token);
    // write out the token to a file so that red5 may be shutdown external to this VM instance.
    try {
        // delete existing file
        Files.deleteIfExists(Paths.get(shutdownTokenFileName));
        // write to file
        Path path = Files.createFile(Paths.get(shutdownTokenFileName));
        File tokenFile = path.toFile();
        RandomAccessFile raf = new RandomAccessFile(tokenFile, "rws");
        raf.write(token.getBytes());
        raf.close();
    } catch (Exception e) {
        log.warn("Exception handling token file", e);
    }
    while (!shutdown.get()) {
        try (ServerSocket serverSocket = new ServerSocket(port);
                Socket clientSocket = serverSocket.accept();
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));) {
            log.info("Connected - local: {} remote: {}", clientSocket.getLocalSocketAddress(),
                    clientSocket.getRemoteSocketAddress());
            String inputLine = in.readLine();
            if (inputLine != null && token.equals(inputLine)) {
                log.info("Shutdown request validated using token");
                out.println("Ok");
                shutdownOrderly();
            } else {
                out.println("Bye");
            }
        } catch (BindException be) {
            log.error("Cannot bind to port: {}, ensure no other instances are bound or choose another port",
                    port, be);
            shutdownOrderly();
        } catch (IOException e) {
            log.warn("Exception caught when trying to listen on port {} or listening for a connection", port,
                    e);
        }
    }
}