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.roda.core.storage.fs.FSUtils.java

/**
 * Deletes a directory/file//w  w w .ja va 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.
 *          in case of a file, if metadata associated to it exists, it will be
 *          deleted as well.
 * @throws NotFoundException
 * @throws GenericException
 */
public static void deletePath(Path path) throws NotFoundException, GenericException {
    if (path == null) {
        return;
    }

    try {
        Files.delete(path);

    } catch (NoSuchFileException e) {
        throw new NotFoundException("Could not delete path", e);
    } catch (DirectoryNotEmptyException e) {
        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 new GenericException("Could not delete entity", e1);
        }
    } catch (IOException e) {
        throw new GenericException("Could not delete entity", e);
    }
}

From source file:com.clust4j.algo.KMedoidsTests.java

@Test
@Override/*from  w ww .jav  a 2 s. com*/
public void testSerialization() throws IOException, ClassNotFoundException {
    KMedoids km = new KMedoids(irisdata, new KMedoidsParameters(3).setVerbose(true)).fit();

    final double c = km.getTSS();
    km.saveObject(new FileOutputStream(TestSuite.tmpSerPath));
    assertTrue(TestSuite.file.exists());

    KMedoids km2 = (KMedoids) KMedoids.loadObject(new FileInputStream(TestSuite.tmpSerPath));
    assertTrue(km2.getTSS() == c);
    assertTrue(km2.equals(km));
    Files.delete(TestSuite.path);
}

From source file:de.ncoder.studipsync.studip.jsoup.JsoupStudipAdapter.java

public void deleteCookies() throws IOException {
    if (cookiesPath != null && Files.exists(cookiesPath)) {
        Files.delete(cookiesPath);
    }//from   w w w.  j a va  2  s .  c  o  m
}

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

@Override
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public String put(InputStream content) throws BinaryStoreServiceException, DataCollisionException {
    try {//  ww  w. j av  a2 s .co  m
        HashedFilterInputStream input = factory.getHashedFilterInputStream(content);
        try {
            Path tmpfile = Paths.get(working.toString(), Long.toString(System.nanoTime()));

            Files.copy(input, tmpfile);
            LOGGER.log(Level.FINE, "content stored in local temporary file: " + tmpfile.toString());
            String hash = input.getHash();
            LOGGER.log(Level.FINE, "content based generated sha1 hash: " + hash);

            String digit = hash.substring(0, DISTINGUISH_SIZE);
            Path volume = Paths.get(base.toString(), BinaryStoreVolumeMapper.getVolume(digit));
            Path parent = Paths.get(base.toString(), BinaryStoreVolumeMapper.getVolume(digit), digit);
            Path file = Paths.get(base.toString(), BinaryStoreVolumeMapper.getVolume(digit), digit, hash);
            if (!Files.exists(volume)) {
                Files.createDirectory(volume);
            }
            if (!Files.exists(parent)) {
                Files.createDirectory(parent);
            }
            if (!Files.exists(file)) {
                Files.move(tmpfile, file);
                LOGGER.log(Level.FINE, "content moved in local definitive file: " + file.toString());
            } else {
                LOGGER.log(Level.FINE, "a file with same hash already exists, trying to detect collision");
                try (InputStream input1 = Files.newInputStream(file);
                        InputStream input2 = Files.newInputStream(tmpfile)) {
                    if (IOUtils.contentEquals(input1, input2)) {
                        Files.delete(tmpfile);
                    } else {
                        LOGGER.log(Level.SEVERE,
                                "BINARY COLLISION DETECTED - storing colliding files in dedicated folder");
                        Files.copy(file, Paths.get(collide.toString(), hash + ".origin"));
                        Files.move(tmpfile, Paths.get(collide.toString(), hash + ".colliding"));
                        throw new DataCollisionException();
                    }
                }
            }
            return hash;
        } catch (IOException | VolumeNotFoundException e) {
            throw new BinaryStoreServiceException(e);
        } finally {
            IOUtils.closeQuietly(input);
        }
    } catch (NoSuchAlgorithmException e) {
        throw new BinaryStoreServiceException(e);
    }
}

From source file:org.apache.taverna.robundle.TestBundles.java

@Test(expected = IOException.class)
public void setMimeTypeMissing() throws Exception {
    try (Bundle bundle = Bundles.createBundle()) {
        Path mimetypePath = bundle.getRoot().resolve("mimetype");
        Files.delete(mimetypePath);
        // sadly now we can't set it (the mimetype file must be uncompressed
        // and at beginning of file,
        // which we don't have the possibility to do now that file system is
        // open)/*  w  ww  .  ja  v a2s. c  o  m*/
        Bundles.setMimeType(bundle, "application/x-test");
    }
}

From source file:models.Attachment.java

/**
 * Deletes this file.//from  w w w .ja v  a 2 s  .c  om
 *
 * This method is used when an user delete an attachment or its container.
 */
@Override
public void delete() {
    super.delete();
    // FIXME: Rarely this may delete a file which is still referred by
    // attachment, if new attachment is added after checking nonexistence
    // of an attachment refers the file and before deleting the file.
    //
    // But synchronization with Attachment class may be a bad idea to solve
    // the problem. If you do that, blocking of project deletion causes
    // that all requests to attachments (even a user avatars you can see in
    // most of pages) are blocked.
    if (!exists(this.hash)) {
        try {
            Files.delete(Paths.get(uploadDirectory, this.hash));
        } catch (Exception e) {
            play.Logger.error("Failed to delete: " + this, e);
        }
    }
}

From source file:org.carcv.impl.core.io.FFMPEGVideoHandlerIT.java

/**
 * Test method for/* www .j  a  va 2  s .c o  m*/
 * {@link org.carcv.impl.core.io.FFMPEGVideoHandler#generateVideoAsStream(java.nio.file.Path, int, java.io.OutputStream)}.
 *
 * @throws IOException
 */
@Test
public void testGenerateVideoAsStreamPathIntOutputStream() throws IOException {
    Path outTemp = Files.createTempFile("testvideo", ".h264");
    OutputStream out = Files.newOutputStream(outTemp);

    FFMPEGVideoHandler.copyCarImagesToDir(entry.getCarImages(), videoDir);
    new FFMPEGVideoHandler().generateVideoAsStream(videoDir, FFMPEGVideoHandler.defaultFrameRate, out);
    assertNotNull(out);
    assertTrue(Files.exists(outTemp));
    assertTrue(Files.isRegularFile(outTemp));

    Files.delete(outTemp);
}

From source file:dk.dma.ais.downloader.QueryService.java

/**
 * Deletes the file specified by the path
 *//*  www.  j a v a2s.c  o m*/
@RequestMapping(value = "/delete/{clientId}/{file:.*}", method = RequestMethod.GET)
@ResponseBody
public String deleteFile(@PathVariable("clientId") String clientId, @PathVariable("file") String file,
        HttpServletResponse response) throws IOException {

    Path path = repoRoot.resolve(clientId).resolve(file);

    if (Files.notExists(path) || Files.isDirectory(path)) {
        log.log(Level.WARNING, "Failed deleting file: " + path);
        response.setStatus(404);
        return "404";
    }

    Files.delete(path);
    log.info("Deleted " + path);
    return "Deleted " + path;
}

From source file:org.roda.core.plugins.plugins.base.ExportAIPPlugin.java

private Report exportMultiZip(List<AIP> aips, Path outputPath, Report report, ModelService model,
        IndexService index, StorageService storage, SimpleJobPluginInfo jobPluginInfo, Job job) {
    for (AIP aip : aips) {
        LOGGER.debug("Exporting AIP {} to ZIP", aip.getId());
        OutputStream os = null;/*from   w w w.  ja v  a 2 s.  c  om*/
        String error = null;
        try {
            Path zip = outputPath.resolve(aip.getId() + ".zip");
            if (FSUtils.exists(zip) && removeIfAlreadyExists) {
                Files.delete(zip);
            } else if (FSUtils.exists(zip) && !removeIfAlreadyExists) {
                error = "File " + zip.toString() + " already exists";
            }
            if (error == null) {
                os = Files.newOutputStream(zip, StandardOpenOption.CREATE,
                        StandardOpenOption.TRUNCATE_EXISTING);

                Directory directory = storage.getDirectory(ModelUtils.getAIPStoragePath(aip.getId()));
                ConsumesOutputStream cos = DownloadUtils.download(storage, directory);
                cos.consumeOutputStream(os);
            }
        } catch (Exception e) {
            LOGGER.error("Error exporting AIP " + aip.getId() + ": " + e.getMessage());
            error = e.getMessage();
        } finally {
            if (os != null) {
                IOUtils.closeQuietly(os);
            }
        }

        Report reportItem = PluginHelper.initPluginReportItem(this, aip.getId(), AIP.class, AIPState.ACTIVE);
        if (error != null) {
            reportItem.setPluginState(PluginState.FAILURE)
                    .setPluginDetails("Export AIP did not end successfully: " + error);
            jobPluginInfo.incrementObjectsProcessedWithFailure();
        } else {
            reportItem.setPluginState(PluginState.SUCCESS).setPluginDetails("Export AIP ended successfully");
            jobPluginInfo.incrementObjectsProcessedWithSuccess();
        }
        report.addReport(reportItem);
        PluginHelper.updatePartialJobReport(this, model, reportItem, true, job);
    }
    return report;
}

From source file:com.joyent.manta.client.MantaClientIT.java

@Test
public final void verifyYouCanJustSpecifyDirNameWhenPuttingFile() throws IOException {
    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    mantaClient.putDirectory(path);//from  w  w w  .j  a  v a2 s.c o  m

    File temp = File.createTempFile("upload", ".txt");

    boolean thrown = false;

    try {
        Files.write(temp.toPath(), TEST_DATA.getBytes(StandardCharsets.UTF_8));
        mantaClient.put(path, temp);
    } catch (MantaClientHttpResponseException e) {
        thrown = e.getStatusCode() == 400;
    } finally {
        Files.delete(temp.toPath());
    }

    Assert.assertTrue(thrown, "Bad request response not received");
}