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_project.commons_ip.model.impl.eark.EARKAIP.java

private Path getDirPath(final Path targetPath, final String name, final boolean deleteExisting)
        throws IPException {
    final Path path;
    if (name != null) {
        path = targetPath.resolve(name);
    } else {/*from  w w w  . jav a2  s.com*/
        path = targetPath.resolve(getId());
    }

    try {
        if (deleteExisting && Files.exists(path)) {
            Files.delete(path);
        }
    } catch (final IOException e) {
        throw new IPException("Error deleting existing path - " + e.getMessage(), e);
    }
    return path;
}

From source file:org.apache.solr.schema.SpatialRPTFieldTypeTest.java

public void testMaxDistErrConversion() throws Exception {
    deleteCore();/*  w  ww. j ava  2s.co m*/
    File managedSchemaFile = new File(tmpConfDir, "managed-schema");
    Files.delete(managedSchemaFile.toPath()); // Delete managed-schema so it won't block parsing a new schema
    System.setProperty("managed.schema.mutable", "true");
    initCore("solrconfig-managed-schema.xml", "schema-one-field-no-dynamic-field.xml", tmpSolrHome.getPath());

    String fieldName = "new_text_field";
    assertNull("Field '" + fieldName + "' is present in the schema",
            h.getCore().getLatestSchema().getFieldOrNull(fieldName));

    IndexSchema oldSchema = h.getCore().getLatestSchema();

    SpatialRecursivePrefixTreeFieldType rptFieldType = new SpatialRecursivePrefixTreeFieldType();
    Map<String, String> rptMap = new HashMap<String, String>();

    rptFieldType.setTypeName("location_rpt");
    rptMap.put("geo", "true");

    // test km
    rptMap.put("distanceUnits", "kilometers");
    rptMap.put("maxDistErr", "0.001"); // 1 meter
    rptFieldType.init(oldSchema, rptMap);
    assertEquals(11, rptFieldType.grid.getMaxLevels());

    // test miles
    rptMap.put("distanceUnits", "miles");
    rptMap.put("maxDistErr", "0.001");
    rptFieldType.init(oldSchema, rptMap);
    assertEquals(10, rptFieldType.grid.getMaxLevels());

    // test degrees
    rptMap.put("distanceUnits", "degrees");
    rptMap.put("maxDistErr", "0.001");
    rptFieldType.init(oldSchema, rptMap);
    assertEquals(8, rptFieldType.grid.getMaxLevels());
}

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

/**
 * Test method for/*ww w . j  a v a  2 s.  co  m*/
 * {@link org.carcv.impl.core.io.FFMPEGVideoHandler#generateVideo(java.nio.file.Path, int, java.nio.file.Path)}.
 *
 * @throws IOException
 */
@Test
public void testGenerateVideoPathIntPath() throws IOException {
    FFMPEGVideoHandler.copyCarImagesToDir(entry.getCarImages(), videoDir);
    Path video = new FFMPEGVideoHandler().generateVideo(videoDir, FFMPEGVideoHandler.defaultFrameRate);
    new FFMPEGVideoHandler().generateVideo(videoDir, FFMPEGVideoHandler.defaultFrameRate);
    assertTrue("Generated Video file doesn't exist.", Files.exists(video));

    Files.delete(video);
}

From source file:ch.mattrero.foldersync.FoldersSynchronizer.java

boolean syncDeleted(final Path sourceItem) {
    final Path backupItem = resolveBackupItemPath(sourceItem);

    try {// w w w .  ja  va  2s  . com
        if (Files.isDirectory(backupItem)) {
            FileUtils.deleteDirectory(backupItem.toFile());
            logger.debug("Deleted directory " + backupItem);
        } else {
            Files.delete(backupItem);
            logger.debug("Deleted file " + backupItem);
        }
    } catch (final IOException e) {
        logger.warn("Failed to delete " + backupItem, e);
        return false;
    }

    return true;
}

From source file:com.kakao.hbase.manager.command.ExportKeysTest.java

@Test
public void testRegex() throws Exception {
    String outputFile = "exportkeys_test.keys";

    try {/*from   w w w  .  j a  v a  2s .  c  o  m*/
        String splitPoint = "splitpoint";
        splitTable(splitPoint.getBytes());
        String tableName2 = createAdditionalTable(tableName + "2");
        splitTable(tableName2, splitPoint.getBytes());

        String tableNameRegex = tableName + ".*";
        String[] argsParam = { "zookeeper", tableNameRegex, outputFile };
        Args args = new ManagerArgs(argsParam);
        assertEquals("zookeeper", args.getZookeeperQuorum());
        ExportKeys command = new ExportKeys(admin, args);

        waitForSplitting(2);
        waitForSplitting(tableName2, 2);
        command.run();

        List<Triple<String, String, String>> results = new ArrayList<>();
        for (String keys : Files.readAllLines(Paths.get(outputFile), Constant.CHARSET)) {

            String[] split = keys.split(ExportKeys.DELIMITER);
            results.add(new ImmutableTriple<>(split[0], split[1], split[2]));
        }
        assertEquals(4, results.size());
    } finally {
        Files.delete(Paths.get(outputFile));
    }
}

From source file:com.microfocus.application.automation.tools.run.JobConfigRebrander.java

/**
 * There are files which can be auto-generated as empty after the package name change.
 * We need to remove them in order to let the
 * {@link JobConfigRebrander#convertXmlFileIfNotExists(TaskListener, File, File)} do the convert.
 * @param listener      a place to send log output
 * @param newFileName   the new file absolute path
 * @param replacedFile  the new file name which we need to remove
 */// ww  w . ja  v a2s  .  c  o m
private void removeXmlFileIfExists(@Nonnull TaskListener listener, String newFileName, File replacedFile) {
    if (replacedFile.exists()) {
        try {
            Files.delete(Paths.get(replacedFile.getAbsolutePath()));
        } catch (IOException | SecurityException e) {
            listener.error("Failed to delete %s when doing Global Settings configurations convert: %s",
                    newFileName, e.getMessage());
            build.setResult(Result.UNSTABLE);
        }
    }
}

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

@Override
public Map<String, Object> processAsset(String site, String folder, String assetName, InputStream in,
        String isImage, String allowedWidth, String allowedHeight, String allowLessSize, String draft,
        String unlock, String systemAsset) {
    String repoPath = UrlUtils.concat(folder, assetName);
    InputStream configIn;/*from   w  ww  .  j a  v a 2 s .  c o m*/

    try {
        try {
            configIn = contentService.getContent(site, configPath);
        } catch (ContentNotFoundException e) {
            // Ignore if file couldn't be found
            configIn = null;
        }

        if (configIn != null) {
            List<ProcessorPipelineConfiguration> pipelinesConfig = configReader.readConfig(configIn);
            if (CollectionUtils.isNotEmpty(pipelinesConfig)) {
                Asset input = createAssetFromInputStream(repoPath, in);
                try {
                    Set<Asset> finalOutputs = new LinkedHashSet<>();

                    for (ProcessorPipelineConfiguration pipelineConfig : pipelinesConfig) {
                        AssetProcessorPipeline pipeline = pipelineResolver.getPipeline(pipelineConfig);
                        List<Asset> outputs = pipeline.processAsset(pipelineConfig, input);

                        if (CollectionUtils.isNotEmpty(outputs)) {
                            finalOutputs.addAll(outputs);
                        }
                    }

                    if (CollectionUtils.isNotEmpty(finalOutputs)) {
                        List<Map<String, Object>> results = writeOutputs(site, finalOutputs, isImage,
                                allowedWidth, allowedHeight, allowLessSize, draft, unlock, systemAsset);

                        // Return first result for now, might be good in the future to consider returning several results or just
                        // one main result specified by config -- Alfonso
                        if (CollectionUtils.isNotEmpty(results)) {
                            return results.get(0);
                        } else {
                            return Collections.emptyMap();
                        }
                    } else {
                        // No outputs mean that the input wasn't matched by any pipeline and processing was skipped
                        logger.debug("No pipeline matched for {0}. Skipping asset processing...", repoPath);

                        // We already read input so open the temp file
                        try (InputStream assetIn = Files.newInputStream(input.getFilePath())) {
                            return contentService.writeContentAsset(site, folder, assetName, assetIn, isImage,
                                    allowedWidth, allowedHeight, allowLessSize, draft, unlock, systemAsset);
                        }
                    }
                } finally {
                    try {
                        Files.delete(input.getFilePath());
                    } catch (IOException e) {
                        // delete silently
                    }
                }
            } else {
                // Ignore if no pipelines config
                logger.debug("No asset processing pipelines config found at {0}. Skipping asset processing...",
                        repoPath);

                return contentService.writeContentAsset(site, folder, assetName, in, isImage, allowedWidth,
                        allowedHeight, allowLessSize, draft, unlock, systemAsset);
            }
        } else {
            logger.debug("No asset processing config found at {0}. Skipping asset processing...", repoPath);

            return contentService.writeContentAsset(site, folder, assetName, in, isImage, allowedWidth,
                    allowedHeight, allowLessSize, draft, unlock, systemAsset);
        }
    } catch (Exception e) {
        logger.error("Error processing asset", e);

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", e.getMessage());
        result.put("error", e);

        return result;
    }
}

From source file:org.nuxeo.ecm.core.api.impl.blob.FileBlob.java

/**
 * Moves this blob's temporary file to a new non-temporary location.
 * <p>/*from w ww . j av a2 s .  co m*/
 * The move is done as atomically as possible.
 *
 * @since 7.2
 */
public void moveTo(File dest) throws IOException {
    if (!isTemporary) {
        throw new IOException("Cannot move non-temporary file: " + file);
    }
    Path path = file.toPath();
    Path destPath = dest.toPath();
    try {
        Files.move(path, destPath, ATOMIC_MOVE);
        file = dest;
    } catch (AtomicMoveNotSupportedException e) {
        // Do a copy through a tmp file on the same filesystem then atomic rename
        Path tmp = Files.createTempFile(destPath.getParent(), null, null);
        try {
            Files.copy(path, tmp, REPLACE_EXISTING);
            Files.delete(path);
            Files.move(tmp, destPath, ATOMIC_MOVE);
            file = dest;
        } catch (IOException ioe) {
            // don't leave tmp file in case of error
            Files.deleteIfExists(tmp);
            throw ioe;
        }
    }
    isTemporary = false;
}

From source file:pinterestbackup.PINDownloader.java

private void removeDeletedPins() {

    if (!config.isSynchronized()) {
        return;// w  ww  .ja v a  2s. c  o  m
    }

    Path deleteFile = null;
    if (this.localFiles != null && this.localFiles.size() > 0) {
        for (Map.Entry<String, Boolean> entry : this.localFiles.entrySet()) {
            if (!entry.getValue()) {
                deleteFile = Paths.get(entry.getKey());
                try {
                    Files.delete(deleteFile);
                } catch (IOException ex) {
                    Logger.getLogger(PinterestBackup.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}

From source file:org.roda_project.commons_ip.model.impl.eark.EARKSIP.java

private Path getZipPath(Path destinationDirectory, String fileNameWithoutExtension) throws IPException {
    Path zipPath;//from   www . j  a v  a2s. c  o  m
    if (fileNameWithoutExtension != null) {
        zipPath = destinationDirectory.resolve(fileNameWithoutExtension + SIP_FILE_EXTENSION);
    } else {
        zipPath = destinationDirectory.resolve(getId() + SIP_FILE_EXTENSION);
    }

    try {
        if (Files.exists(zipPath)) {
            Files.delete(zipPath);
        }
    } catch (IOException e) {
        throw new IPException("Error deleting already existing zip", e);
    }
    return zipPath;
}