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:org.sonar.core.util.FileUtils.java

/**
 * Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.
 * <p>/*from  ww w. ja v  a  2s .  com*/
 * The difference between File.delete() and this method are:
 * <ul>
 * <li>A directory to be deleted does not have to be empty.</li>
 * <li>No exceptions are thrown when a file or directory cannot be deleted.</li>
 * </ul>
 *
 * @param file  file or directory to delete, can be {@code null}
 * @return {@code true} if the file or directory was deleted, otherwise {@code false}
 */
public static boolean deleteQuietly(@Nullable File file) {
    if (file == null) {
        return false;
    }

    try {
        if (file.isDirectory()) {
            deleteDirectory(file);
        } else {
            Files.delete(file.toPath());
        }
        return true;
    } catch (IOException | SecurityException ignored) {
        return false;
    }
}

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

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

    if (logoDirectory == null) {
        synchronized (this) {
            if (logoDirectory == null) {
                logoDirectory = Resources.locateHarvesterLogosDir(context);
            }/*from   w ww .  j a va2 s .co  m*/
        }
    }

    String file = Util.getParam(params, Params.FNAME);

    FilePathChecker.verify(file);

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

    Path logoFile = logoDirectory.resolve(file);

    Element response = new Element("response");
    Files.delete(logoFile);
    response.addContent(new Element("status").setText("Logo removed."));
    return response;
}

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

/**
 * Deletes a whole directory (recursively)
 * <p>//  ww w . j  a  v  a 2  s.c  o m
 * @param aDir
 *        a folder to be deleted (must not be null)
 * @throws IOException
 */
public static void deleteDirRecursive(Path aDir) throws IOException {
    if (aDir == null) {
        throw new IllegalArgumentException("aDir must not be null");
    }

    if (Files.notExists(aDir)) {
        return;
    }

    if (!Files.isDirectory(aDir)) {
        throw new IllegalArgumentException("given aDir is not a directory");
    }

    Files.walkFileTree(aDir, new SimpleFileVisitor<Path>() {
        /**
         * @see java.nio.file.SimpleFileVisitor#visitFileFailed(java.lang.Object, java.io.IOException)
         */
        @Override
        public FileVisitResult visitFileFailed(Path aFile, IOException aExc) throws IOException {
            if ("System Volume Information".equals((aFile.getFileName().toString()))) {
                return FileVisitResult.SKIP_SUBTREE;
            }

            throw aExc;
        }

        /**
         * @see java.nio.file.SimpleFileVisitor#preVisitDirectory(java.lang.Object, java.nio.file.attribute.BasicFileAttributes)
         */
        @Override
        public FileVisitResult preVisitDirectory(Path aFile, BasicFileAttributes aAttrs) throws IOException {
            if ("System Volume Information".equals((aFile.getFileName()))) {
                return FileVisitResult.SKIP_SUBTREE;
            }

            return FileVisitResult.CONTINUE;
        }

        @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 (dir.isAbsolute() && dir.getRoot().equals(dir)) {
                myLog.debug("root cannot be deleted: " + dir.toString());
                return FileVisitResult.CONTINUE;
            }

            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }

    });
}

From source file:fi.johannes.kata.ocr.utils.files.ExistingFileConnection.java

public void delete() throws IOException {
    Files.delete(p);
}

From source file:org.wso2.msf4j.perftest.echo.springboot.EchoService.java

@RequestMapping("/EchoService/fileecho")
@ResponseBody//from   w  w w.j  a va  2  s  .c  o  m
public String fileWrite(@RequestBody String body) throws InterruptedException, IOException {
    String returnStr = "";
    java.nio.file.Path tempfile = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
    Files.write(tempfile, body.getBytes(Charset.defaultCharset()), StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING);
    returnStr = new String(Files.readAllBytes(tempfile), Charset.defaultCharset());
    Files.delete(tempfile);
    return returnStr;
}

From source file:car_counter.storage.sqlite.TestSqliteStorage.java

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

From source file:org.craftercms.studio.impl.v1.asset.processing.AbstractAssetProcessor.java

@Override
public Asset processAsset(ProcessorConfiguration config, Matcher inputPathMatcher, Asset input)
        throws AssetProcessingException {
    try {//from  ww w  .ja v a  2s  . c  om
        String outputRepoPath = getOutputRepoPath(config, inputPathMatcher);
        if (StringUtils.isEmpty(outputRepoPath)) {
            // No output repo path means write to the same input. So move the original file to a tmp location
            // and make the output file be the input file
            Path inputFilePath = moveToTmpFile(input.getRepoPath(), input.getFilePath());
            Path outputFilePath = input.getFilePath();
            Asset output = new Asset(input.getRepoPath(), outputFilePath);

            logger.info("Asset processing: Type = {}, Input = {}, Output = {}", config.getType(), input,
                    output);

            try {
                doProcessAsset(inputFilePath, outputFilePath, config.getParams());
            } finally {
                Files.delete(inputFilePath);
            }

            return output;
        } else {
            Path inputFilePath = input.getFilePath();
            Path outputFilePath = createTmpFile(outputRepoPath);
            Asset output = new Asset(outputRepoPath, outputFilePath);

            logger.info("Asset processing: Type = {}, Input = {}, Output = {}", config.getType(), input,
                    output);

            doProcessAsset(inputFilePath, outputFilePath, config.getParams());

            return output;
        }
    } catch (Exception e) {
        throw new AssetProcessingException(
                "Error while executing asset processor of type '" + config.getType() + "'", e);
    }
}

From source file:fr.duminy.jbackup.core.archive.CompressorTest.java

@Test
public void testCompress_relativeFilesMustThrowAnException() throws Throwable {
    ArchiveFactory mockFactory = createMockArchiveFactory(mock(ArchiveOutputStream.class));
    Path relativeFile = Paths.get("testCompressRelativeFile.tmp");

    try {//from   www .  j  a  v a2s . c  o  m
        createFile(relativeFile, 1);

        thrown.expect(IllegalArgumentException.class);
        thrown.expectMessage(String.format("The file '%s' is relative.", relativeFile));

        final ArchiveParameters archiveParameters = new ArchiveParameters(createArchivePath(), false);
        archiveParameters.addSource(relativeFile);
        compress(mockFactory, archiveParameters, null, null);
    } finally {
        Files.delete(relativeFile);
    }
}

From source file:org.springframework.cloud.gcp.storage.integration.inbound.GcsInboundFileSynchronizerTests.java

@After
@Before//ww  w.j ava 2 s. c  o  m
public void cleanUp() throws IOException {
    Path testDirectory = Paths.get("test");

    if (Files.exists(testDirectory)) {
        if (Files.isDirectory(testDirectory)) {
            try (Stream<Path> files = Files.list(testDirectory)) {
                files.forEach((path) -> {
                    try {
                        Files.delete(path);
                    } catch (IOException ioe) {
                        LOGGER.info("Error deleting test file.", ioe);
                    }
                });
            }
        }

        Files.delete(testDirectory);
    }
}

From source file:br.pucminas.ri.jsearch.rest.controller.ApiController.java

public static Object fileUpload(Request req, Response res) {
    req.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("/temp"));
    Path out = Paths.get("result/queries.txt");

    try (InputStream is = req.raw().getPart("uploaded_file").getInputStream()) {
        Path folder = Paths.get("result");
        if (Files.exists(folder)) {
            Files.delete(out);
        }/*from w  ww. ja  v a 2s.  c o  m*/
        Files.createDirectories(Paths.get("result"));
        Files.copy(is, out);
        return evalTests(req, res);
    } catch (IOException | ServletException e) {
        e.printStackTrace();
        return "Error on upload file";
    }
}