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:de.elomagic.carafile.server.CloudTest.java

@RunAsClient
@Test/* ww  w.  ja va 2s .c o  m*/
public void testCloudUpload() throws Exception {
    Runnable r = () -> {
        try {
            cloud.start();
        } catch (Exception ex) {
            cex = ex;
        }
    };
    new Thread(r).start();

    // Create file
    Thread.sleep(2000);
    Path file = Files.createTempFile(basePath, "TESTFILE_", ".txt");

    // Check in the repository folder
    int loop = 10;
    while (loop-- > 0) {
        Thread.sleep(2000);
        Set<CloudFileData> set = cloud.list(Paths.get(""));
        if (set.size() == 1) {
            System.out.println("One item found in the folder. Bingo !!!");
            break;
        }
    }
    if (loop <= 0) {
        Assert.fail("Remote folder not equals one");
    }

    // Delete file
    Files.delete(file);

    // Check in the repository folder
    loop = 10;
    while (loop-- > 0) {
        Thread.sleep(2000);
        Set<CloudFileData> set = cloud.list(Paths.get(""));
        if (set.isEmpty()) {
            System.out.println("No item found in the folder. Bingo !!!");
            break;
        }
    }
    if (loop <= 0) {
        Assert.fail("Remote folder not empty");
    }

    // Check in the repository folder
    if (cex != null) {
        throw cex;
    }

    cloud.stop();
}

From source file:de.alexkamp.sandbox.ChrootSandboxFactory.java

@Override
public void deleteSandbox(final SandboxData sandbox) {
    File copyDir = sandbox.getBaseDir();

    try {//from   www .  ja  v  a  2 s. c  o m
        final AtomicInteger depth = new AtomicInteger(0);
        Files.walkFileTree(copyDir.toPath(), new FileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes basicFileAttributes)
                    throws IOException {
                int d = depth.getAndIncrement();

                // see whether the mounts are gone
                if (1 == d) {
                    for (Mount m : sandbox) {
                        if (path.endsWith(m.getMountPoint().substring(1))) {
                            if (0 != path.toFile().listFiles().length) {
                                throw new IllegalArgumentException(
                                        path.getFileName() + " has not been unmounted.");
                            }
                        }
                    }
                }

                return FileVisitResult.CONTINUE;
            }

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

            @Override
            public FileVisitResult visitFileFailed(Path path, IOException e) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path path, IOException e) throws IOException {
                Files.delete(path);
                depth.decrementAndGet();
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new SandboxException(e);
    }
}

From source file:io.lavagna.web.api.SetupController.java

@RequestMapping(value = "/setup/api/import", method = RequestMethod.POST)
public void importLavagna(@RequestParam("file") MultipartFile file, HttpServletRequest req,
        HttpServletResponse res) throws IOException {

    // TODO: move to a helper, as it has the same code as the one in the ExportImportController
    Path tempFile = Files.createTempFile(null, null);
    try {/*from   w w w.  j  a v a 2s  . co m*/
        try (InputStream is = file.getInputStream(); OutputStream os = Files.newOutputStream(tempFile)) {
            StreamUtils.copy(is, os);
        }
        exportImportService2.importData(true, tempFile);
    } finally {
        Files.delete(tempFile);
    }
    //

    res.sendRedirect(req.getServletContext().getContextPath());
}

From source file:io.personium.core.model.file.StreamingOutputForDavFileWithRange.java

@Override
public void write(OutputStream output) throws IOException, WebApplicationException {
    try {/*ww w .j  a v a2  s  .c  om*/
        // MultiPart???????1?byte-renge-set????
        int rangeIndex = 0;
        List<ByteRangeSpec> brss = range.getByteRangeSpecList();
        final ByteRangeSpec brs = brss.get(rangeIndex);

        int chr;
        long first = brs.getFirstBytePos();
        long last = brs.getLastBytePos();
        // Range??????
        if (hardLinkInput.skip(first) != first) {
            PersoniumCoreLog.Dav.FILE_TOO_SHORT.params("skip failed", fileSize, range.getRangeHeaderField())
                    .writeLog();
            throw PersoniumCoreException.Dav.FS_INCONSISTENCY_FOUND;
        }
        // Range????
        for (long pos = first; pos < last + 1; pos++) {
            chr = hardLinkInput.read();
            if (chr == -1) {
                PersoniumCoreLog.Dav.FILE_TOO_SHORT
                        .params("too short.size", fileSize, range.getRangeHeaderField()).writeLog();
                throw PersoniumCoreException.Dav.FS_INCONSISTENCY_FOUND;
            }
            output.write((char) chr);
        }
    } finally {
        IOUtils.closeQuietly(hardLinkInput);
        Files.delete(hardLinkPath);
    }
}

From source file:au.org.ands.vocabs.toolkit.provider.harvest.FileHarvestProvider.java

/** Do a harvest. Update the message parameter with the result
 * of the harvest.//from  w  w w .  j a  v  a2s  .com
 * NB: if delete is true, Tomcat must have write access, in order
 * to be able to delete the file successfully. However, a failed
 * deletion will not per se cause the subtask to fail.
 * @param version The version to which access points are to be added.
 * @param format The format of the file(s) to be harvested.
 * @param filePath The path to the file or directory to be harvested.
 * @param outputPath The directory in which to store output files.
 * @param delete True, if successfully harvested files are to be deleted.
 * @param results HashMap representing the result of the harvest.
 * @return True, iff the harvest succeeded.
 */
public final boolean getHarvestFiles(final Version version, final String format, final String filePath,
        final String outputPath, final boolean delete, final HashMap<String, String> results) {
    ToolkitFileUtils.requireDirectory(outputPath);
    Path filePathPath = Paths.get(filePath);
    Path outputPathPath = Paths.get(outputPath);
    if (Files.isDirectory(filePathPath)) {
        logger.debug("Harvesting file(s) from directory " + filePath);
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(filePathPath)) {
            for (Path entry : stream) {
                // Only harvest files. E.g., no recursive
                // directory searching.
                if (Files.isRegularFile(entry)) {
                    logger.debug("Harvesting file:" + entry.toString());
                    Path target = outputPathPath.resolve(entry.getFileName());
                    Files.copy(entry, target, StandardCopyOption.REPLACE_EXISTING);
                    AccessPointUtils.createFileAccessPoint(version, format, target);
                    if (delete) {
                        logger.debug("Deleting file: " + entry.toString());
                        try {
                            Files.delete(entry);
                        } catch (AccessDeniedException e) {
                            logger.error("Unable to delete file: " + entry.toString(), e);
                        }
                    }
                }
            }
        } catch (DirectoryIteratorException | IOException ex) {
            results.put(TaskStatus.EXCEPTION, "Exception in getHarvestFiles while copying file");
            logger.error("Exception in getHarvestFiles while copying file:", ex);
            return false;
        }
    } else {
        logger.debug("Harvesting file: " + filePath);
        try {
            Path target = outputPathPath.resolve(filePathPath.getFileName());
            Files.copy(filePathPath, target, StandardCopyOption.REPLACE_EXISTING);
            AccessPointUtils.createFileAccessPoint(version, format, target);
            if (delete) {
                logger.debug("Deleting file: " + filePathPath.toString());
                try {
                    Files.delete(filePathPath);
                } catch (AccessDeniedException e) {
                    logger.error("Unable to delete file: " + filePathPath.toString(), e);
                }
            }
        } catch (IOException e) {
            results.put(TaskStatus.EXCEPTION, "Exception in getHarvestFiles while copying file");
            logger.error("Exception in getHarvestFiles while copying file:", e);
            return false;
        }
    }
    // If we reached here, success, so return true.
    return true;
}

From source file:org.apache.beam.sdk.extensions.sql.impl.schema.text.BeamTextCSVTableTest.java

@AfterClass
public static void teardownClass() throws IOException {
    Files.walkFileTree(tempFolder, new SimpleFileVisitor<Path>() {

        @Override//from  w  ww. j  a va2 s  .  c o m
        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;
        }
    });
}

From source file:io.druid.query.groupby.epinephelinae.LimitedTemporaryStorage.java

public void delete(final File file) {
    synchronized (files) {
        if (files.contains(file)) {
            try {
                Files.delete(file.toPath());
            } catch (IOException e) {
                log.warn(e, "Cannot delete file: %s", file);
            }//w ww .  j  a v a2s .  com
            files.remove(file);
        }
    }
}

From source file:org.dhus.store.datastore.hfs.HfsManager.java

/**
 * Properly delete a path in HFSManager directory.
 * If the path is not inside the HFSManager path, it will not be removed.
 *
 * @param path the path to delete./*w w  w . j av  a 2 s  . c o m*/
 * @throws IOException
 */
public void delete(String path) throws IOException {
    Objects.requireNonNull(path, "Path is null");
    LOGGER.debug("Delete of path {}", path);

    File container = new File(path);
    // Case of path not inside hfsManager: do not remove !
    if (!container.exists() || !isContaining(container)) {
        return;
    }
    // We first delete the file
    Files.delete(Paths.get(path));
    // Case of path basename matches the 'old' reserved "dhus_entry" folder
    if (HierarchicalDirectoryBuilder.DHUS_ENTRY_NAME.equals(container.getParentFile().getName())) {
        container = container.getParentFile();
        // Force recursive delete of the folder
        if (container != null) {
            try {
                Files.delete(container.toPath());
            } catch (DirectoryNotEmptyException suppressed) {
            } catch (IOException ex) {
                LOGGER.warn("Unable de delete directory {}", container);
            }
        }
    }
}

From source file:nl.mpi.lamus.filesystem.implementation.LamusWorkspaceFileHandler.java

/**
 * @see WorkspaceFileHandler#moveFile(java.io.File, java.io.File)
 *//*from   ww w  .  ja v a  2  s .c o  m*/
@Override
public void moveFile(File originNodeFile, File targetNodeFile) throws IOException {
    //file was probably not uploaded via lamus. Move target file if symbolic link
    if (Files.isSymbolicLink(originNodeFile.toPath())) {
        File originLinkToNodeFile = originNodeFile;
        originNodeFile = Files.readSymbolicLink(originNodeFile.toPath()).toFile();
        moveOrCopyFile(originNodeFile, targetNodeFile);
        Files.delete(originLinkToNodeFile.toPath());
    } else {
        moveOrCopyFile(originNodeFile, targetNodeFile);
    }
}

From source file:org.openmrs.module.radiology.report.template.MrrtReportTemplateServiceImpl.java

/**
 * @see org.openmrs.module.radiology.report.template.MrrtReportTemplateService#purgeMrrtReportTemplate(MrrtReportTemplate)
 *//*w w  w. j  a  v a 2s .c  o m*/
@Override
@Transactional
public void purgeMrrtReportTemplate(MrrtReportTemplate template) {
    if (template == null) {
        throw new IllegalArgumentException("template cannot be null");
    }
    mrrtReportTemplateDAO.purgeMrrtReportTemplate(template);
    Path templatePath = Paths.get(template.getPath());
    try {
        Files.delete(templatePath);
    } catch (NoSuchFileException noSuchFileException) {
        log.debug("Tried to delete " + template.getPath() + " , but wasnt found.");
    } catch (IOException ioException) {
        throw new APIException("radiology.MrrtReportTemplate.delete.error.fs", null, ioException);
    }
}