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:com.cloudbees.clickstack.util.Files2.java

/**
 * Delete given {@code dir} and its content ({@code rm -rf}).
 *
 * @param dir/*  w  ww . j  av  a2 s.  co m*/
 * @throws RuntimeIOException
 */
public static void deleteDirectory(@Nonnull Path dir) throws RuntimeIOException {
    try {
        Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

                logger.trace("Delete file: {} ...", file);
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {

                if (exc == null) {
                    logger.trace("Delete dir: {} ...", dir);
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                } else {
                    throw exc;
                }
            }

        });
    } catch (IOException e) {
        throw new RuntimeIOException("Exception deleting '" + dir + "'", e);
    }
}

From source file:org.reactor.monitoring.util.FileHandler.java

public static void createAndUpdateFile(final boolean replaceFile, final String fileLocation,
        final String output) {
    try {// w w w.j a  va 2s  .  c  o  m
        Path path = Paths.get(fileLocation);
        Path parentDir = path.getParent();
        if (!Files.exists(parentDir)) {
            Files.createDirectories(parentDir);
        }

        if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
            Files.createFile(path);
        } else if (replaceFile) {
            Files.delete(path);
            Files.createFile(path);
        }

        Files.write(path, output.getBytes(), StandardOpenOption.APPEND);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:ch.puzzle.itc.mobiliar.business.utils.SecureFileLoaderTest.java

@Test
public void testIsFileLocatedInDirectoryHomeAlthoughExistsNok() throws IOException {
    Path f2 = Paths.get(FileUtils.getTempDirectoryPath(), "test.txt");
    try {//from   www  .  j a va 2s . com
        Files.createFile(f2);
    } catch (FileAlreadyExistsException e) {
        //Only thrown on Windows
    }

    Assert.assertFalse(fileLoader.isFileLocatedInDirectory(dir, f2));
    Files.delete(f2);
}

From source file:org.jetbrains.webdemo.backend.executor.ExecutorUtils.java

public static ExecutionResult executeCompiledFiles(Map<String, byte[]> files, String mainClass,
        List<Path> kotlinRuntimeJars, String arguments, Path executorsPolicy, boolean isJunit)
        throws Exception {
    Path codeDirectory = null;//  ww  w.ja va2  s .co m
    try {
        codeDirectory = storeFilesInTemporaryDirectory(files);
        JavaExecutorBuilder executorBuilder = new JavaExecutorBuilder().enableAssertions().setMemoryLimit(32)
                .enableSecurityManager().setPolicyFile(executorsPolicy).addToClasspath(kotlinRuntimeJars)
                .addToClasspath(jarFiles).addToClasspath(codeDirectory);
        if (isJunit) {
            executorBuilder.addToClasspath(junit);
            executorBuilder.addToClasspath(hamcrest);
            executorBuilder.setMainClass("org.jetbrains.webdemo.executors.JunitExecutor");
            executorBuilder.addArgument(codeDirectory.toString());
        } else {
            executorBuilder.setMainClass("org.jetbrains.webdemo.executors.JavaExecutor");
            executorBuilder.addArgument(mainClass);
        }

        for (String argument : arguments.split(" ")) {
            if (argument.trim().isEmpty())
                continue;
            executorBuilder.addArgument(argument);
        }

        ProgramOutput output = executorBuilder.build().execute();
        return parseOutput(output.getStandardOutput(), isJunit);
    } finally {
        try {
            if (codeDirectory != null) {
                Files.walkFileTree(codeDirectory, new FileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        return FileVisitResult.CONTINUE;
                    }

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

                    @Override
                    public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                        return FileVisitResult.TERMINATE;
                    }

                    @Override
                    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                        Files.delete(dir);
                        return FileVisitResult.CONTINUE;
                    }
                });
            }
        } catch (IOException e) {
            ErrorWriter.getInstance().writeExceptionToExceptionAnalyzer(e, "Can't delete code directory");
        }
    }
}

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

@AfterClass
public static void afterTest() throws IOException {
    Files.deleteIfExists(tempFilePath);
    Path storePath = Paths.get(System.getProperty("user.home") + File.separator + "testfilestore");
    try {/*from  w w  w  .  ja v a  2s  . c  o m*/
        Files.walkFileTree(storePath, new SimpleFileVisitor<Path>() {

            @Override
            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 {
                if (exc == null) {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                } else {
                    throw exc;
                }
            }

        });
    } catch (IOException e) {

    }
}

From source file:org.nuxeo.connect.tests.TestIDGens.java

@Test(expected = InvalidCLID.class)
public void testInvalidCLID() throws IOException, InvalidCLID {
    Path tempCLID = Files.createTempFile("instance", ".clid");
    Files.write(tempCLID, "invalid CLID with only one line".getBytes());
    try {/*from w w w .  ja va 2s. c om*/
        LogicalInstanceIdentifier.load(tempCLID.toString());
    } finally {
        Files.delete(tempCLID);
    }
}

From source file:fr.ortolang.diffusion.store.binary.BinaryStoreServiceTest.java

@After
public void tearDown() {
    try {/*from www .  j  a va 2s. c  om*/
        Files.walkFileTree(service.getBase(), new FileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return FileVisitResult.CONTINUE;
            }

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

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                LOGGER.log(Level.SEVERE, "unable to purge temporary created filesystem", exc);
                return FileVisitResult.TERMINATE;
            }

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

        });
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
}

From source file:car_counter.processing.TestDefaultProcessor.java

@After
public void tearDown() throws Exception {
    Files.delete(dbFile);
    FileUtils.deleteDirectory(tempDirectory.toFile());
}

From source file:org.roda_project.commons_ip.utils.Utils.java

/**
 * Deletes a directory/file/* w w  w  .  ja  v a 2s . co  m*/
 * 
 * @param path
 *          path to the directory/file that will be deleted. in case of a
 *          directory, if not empty, everything in it will be deleted as well.
 *
 * @throws IOException
 */
public static void deletePath(Path path) throws IOException {
    if (path == null) {
        return;
    }

    try {
        Files.delete(path);

    } catch (DirectoryNotEmptyException e) {
        LOGGER.debug("Directory is not empty. Going to delete its content as well.");
        try {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                @Override
                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;
                }

            });
        } catch (IOException e1) {
            throw e1;
        }
    } catch (IOException e) {
        throw e;
    }
}

From source file:com.netscape.cmstools.profile.ProfileEditCLI.java

public void execute(String[] args) throws Exception {
    // Always check for "--help" prior to parsing
    if (Arrays.asList(args).contains("--help")) {
        printHelp();/*from www.  j  a  v a 2 s  . c o  m*/
        return;
    }

    CommandLine cmd = parser.parse(options, args);

    String[] cmdArgs = cmd.getArgs();

    if (cmdArgs.length < 1) {
        throw new Exception("No Profile ID specified.");
    }

    String profileId = cmdArgs[0];

    ProfileClient profileClient = profileCLI.getProfileClient();

    // read profile into temporary file
    byte[] orig = profileClient.retrieveProfileRaw(profileId);
    ProfileCLI.checkConfiguration(orig, false /* requireProfileId */, true /* requireDisabled */);
    Path tempFile = Files.createTempFile("pki", ".cfg");

    try {
        Files.write(tempFile, orig);

        // invoke editor on temporary file
        String editor = System.getenv("EDITOR");
        String[] command;
        if (editor == null || editor.trim().isEmpty()) {
            command = new String[] { "/usr/bin/env", "vi", tempFile.toString() };
        } else {
            command = new String[] { editor.trim(), tempFile.toString() };
        }
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.inheritIO();
        int exitCode = pb.start().waitFor();
        if (exitCode != 0) {
            throw new Exception("Exited abnormally.");
        }

        // read data from temporary file and modify if changed
        byte[] cur = ProfileCLI.readRawProfileFromFile(tempFile);
        if (!Arrays.equals(cur, orig)) {
            profileClient.modifyProfileRaw(profileId, cur);
        }
        System.out.write(cur);
    } finally {
        Files.delete(tempFile);
    }
}