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.fao.geonet.kernel.harvest.harvester.geonet.Aligner.java

private void removeOldFile(String id, Element infoFiles, String dir) {
    Path resourcesDir = Lib.resource.getDir(context, dir, id);

    try (DirectoryStream<Path> paths = Files.newDirectoryStream(resourcesDir)) {
        for (Path file : paths) {
            if (file != null && file.getFileName() != null && infoFiles != null
                    && !existsFile(file.getFileName().toString(), infoFiles)) {
                if (log.isDebugEnabled()) {
                    log.debug("  - Removing old " + dir + " file with name=" + file.getFileName());
                }//from   w  ww.  j  a  v  a  2s . c o m
                try {
                    Files.delete(file);
                } catch (IOException e) {
                    log.warning("Unable to delete file: " + file);
                }
            }
        }
    } catch (IOException e) {
        log.error("  - Cannot scan directory for " + dir + " files : "
                + resourcesDir.toAbsolutePath().normalize());
    }
}

From source file:fmiquerytest.Coordinates.java

static void cleanupOldWeatherData(int daysToStoreWeatherData) {
    int cleanUpTime = parseInt(FmiQueryTest.df_daycode
            .format(new Date(System.currentTimeMillis() - ((daysToStoreWeatherData * 24 * 3600) * 1000))));
    File dir = new File(".");
    FilenameFilter filter = new FilenameFilter() {
        @Override/*from  w  ww  . ja  v a 2  s.  c om*/
        public boolean accept(File dir, String name) {
            return name.startsWith("weather");
        }
    };
    String[] weatherFiles = dir.list(filter);
    System.out.println("Cleaning up old weather data from directory:");
    for (String file : weatherFiles) {
        System.out.print(file);
        int currentDayCode = parseInt(file.replaceAll("weather", "").substring(0, 8));
        if (currentDayCode <= cleanUpTime) {
            try {
                Files.delete(FileSystems.getDefault().getPath(file));
            } catch (IOException ex) {
                Logger.getLogger(FileSystemTools.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println(" - was removed.");
        } else {
            System.out.println(" - was kept.");
        }
    }
}

From source file:com.spectralogic.ds3client.integration.Smoke_Test.java

@Test
public void partialGetWithBookOverChunkBoundry()
        throws IOException, XmlProcessingException, URISyntaxException {
    final String bucketName = "partialGetOnBook";
    final Path filePath = Files.createTempFile("ds3", "lesmis-copies.txt");
    LOG.info("TempFile for partial get of book: " + filePath.toAbsolutePath().toString());

    try {//from   w w  w  . j  a  v a 2  s.co  m

        HELPERS.ensureBucketExists(bucketName, envDataPolicyId);

        final List<Ds3Object> putObjects = Lists.newArrayList(new Ds3Object("lesmis-copies.txt", 13290604));

        final Ds3ClientHelpers.Job putJob = HELPERS.startWriteJob(bucketName, putObjects, WriteJobOptions
                .create().withMaxUploadSize(PutBulkJobSpectraS3Request.MIN_UPLOAD_SIZE_IN_BYTES));

        putJob.transfer(new ResourceObjectPutter("largeFiles/"));

        final List<Ds3Object> getObjects = Lists.newArrayList();
        getObjects.add(new PartialDs3Object("lesmis-copies.txt", Range.byLength(1048476, 200)));

        final Ds3ClientHelpers.Job getJob = HELPERS.startReadJob(bucketName, getObjects);

        getJob.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() {
            @Override
            public SeekableByteChannel buildChannel(final String key) throws IOException {
                return Files.newByteChannel(filePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
            }
        });

        final Path expectedResultPath = Paths.get(Smoke_Test.class.getResource("/largeFiles/output").toURI());

        assertThat(Files.size(filePath), is(200L));
        final String partialFile = new String(Files.readAllBytes(filePath), Charset.forName("UTF-8"));
        final String expectedResult = new String(Files.readAllBytes(expectedResultPath),
                Charset.forName("UTF-8"));
        assertThat(partialFile, is(expectedResult.substring(0, expectedResult.length() - 1))); // need the trim to remove a newline that is added by the os
    } finally {
        deleteAllContents(client, bucketName);
        Files.delete(filePath);
    }
}

From source file:org.apache.openaz.xacml.admin.components.PolicyWorkspace.java

protected void savePolicy(final Path newPolicyPath, final Object policyData, Path oldPolicyPath) {
    ////from   w  w  w .  j  a  v a  2s. c  o m
    // Are they overwriting another policy?
    //
    String version = "1.0";
    boolean delete = false;
    if (oldPolicyPath != null) {
        //
        // This policy name was being edited. Is it still the same?
        //
        try {
            delete = true;
            if (Files.exists(newPolicyPath) && Files.isSameFile(newPolicyPath, oldPolicyPath)) {
                delete = false;
            }
        } catch (Exception e) {
            logger.error("Could not determine if same file", e);
            return;
        }
        logger.info("Deleting old file: " + delete);
    }
    //
    // Are we now overwriting another file?
    //
    if (Files.exists(newPolicyPath)) {
        //
        // Yes
        //
        logger.info("Overwriting file");
        //
        // Overwrite is happening. Bump the version (IF WE CAN)
        //
        //TODO - What if user wants to change something other than the last number?  For example, changing 1.5.23 to 2.0.0.
        //TODO     We need a mechanism that allows the user to specify the new policy version (disallowing backtracking) if they desire
        //TODO     and get that new number (if any) passed down to here.  This code then becomes the "then" branch of "If new version has been specified..."
        try {
            int[] versionArray = StdPDPPolicy
                    .versionStringToArray(XACMLPolicyScanner.getVersion(newPolicyPath));
            // increment the right-most digit
            versionArray[versionArray.length - 1]++;
            version = StdPDPPolicy.versionArrayToString(versionArray);
        } catch (NumberFormatException | IOException e) {
            try {
                logger.warn("Previous version '" + XACMLPolicyScanner.getVersion(newPolicyPath)
                        + "' not a series of itegers");
            } catch (IOException e1) {
                logger.error("could not get previous version");
            }
            //TODO - This may not be wise since the intent is to increase the version number.  Perhaps we should abort this an go back to the user?
            version = "1.0";
        }
        if (policyData instanceof PolicySetType) {
            ((PolicySetType) policyData).setVersion(version);
        } else if (policyData instanceof PolicyType) {
            ((PolicyType) policyData).setVersion(version);
        }
    } else {
        //
        // Nope, a completely new file
        //
        logger.info("New file");
    }
    //
    // Is the root a PolicySet or Policy?
    //
    Path finalPolicyPath;
    if (policyData instanceof PolicySetType) {
        //
        // Write it out
        //
        finalPolicyPath = XACMLPolicyWriter.writePolicyFile(newPolicyPath, (PolicySetType) policyData);
    } else if (policyData instanceof PolicyType) {
        //
        // Write it out
        //
        finalPolicyPath = XACMLPolicyWriter.writePolicyFile(newPolicyPath, (PolicyType) policyData);
    } else {
        logger.error("Unknown data type sent back.");
        return;
    }
    //
    // Did it get written?
    //
    if (finalPolicyPath == null || !Files.exists(finalPolicyPath)) {
        logger.error("Failed to write policy file.");
        return;
    }
    //
    // Add it into our tree
    //
    this.addPolicyFileToTree(finalPolicyPath.getParent().toFile(), finalPolicyPath.toFile());
    //
    // Do we need to delete the old file?
    //
    if (oldPolicyPath != null && delete) {
        try {
            Files.delete(oldPolicyPath);
        } catch (Exception e) {
            logger.error("Failed to delete old policy", e);
        }
        if (self.treeWorkspace.removeItem(oldPolicyPath.toFile()) == false) {
            logger.warn("Failed to remove old policy path");
        }
    }
}

From source file:org.apache.taverna.databundle.TestDataBundles.java

@Test(expected = FileAlreadyExistsException.class)
public void getIntermediatesFails() throws Exception {
    Path intermediates = DataBundles.getIntermediates(dataBundle);
    Files.delete(intermediates);
    Files.createFile(intermediates);
    DataBundles.getIntermediates(dataBundle);
}

From source file:edu.jhuapl.tinkerpop.AccumuloGraphConfiguration.java

private File createTempDir() throws IOException {
    File temp = File.createTempFile(AccumuloGraphConfiguration.class.getSimpleName(), ".mini.tmp");
    Files.delete(temp.toPath());
    Files.createDirectory(temp.toPath());
    return temp;//from ww  w .jav  a2  s  .co m
}

From source file:fr.pilato.elasticsearch.crawler.fs.test.integration.FsCrawlerImplAllParametersIT.java

/**
 * Test case for #95: https://github.com/dadoonet/fscrawler/issues/95 : Folder index is not getting delete on delete of folder
 *//*  w w  w .  jav  a 2  s.  c  om*/
@Test
public void test_remove_folder_deleted_enabled() throws Exception {
    Fs fs = startCrawlerDefinition().setRemoveDeleted(true).build();
    startCrawler(getCrawlerName(), fs, endCrawlerDefinition(getCrawlerName()), null);

    // We should have 7 docs first
    countTestHelper(getCrawlerName(), null, 7, currentTestResourceDir);

    logContentOfDir(currentTestResourceDir, Level.DEBUG);

    // We remove a directory
    logger.info("  ---> Removing dir subdir1");
    Files.walkFileTree(currentTestResourceDir.resolve("subdir1"), 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;
        }
    });

    logContentOfDir(currentTestResourceDir, Level.DEBUG);

    // We expect to have 4 docs now
    countTestHelper(getCrawlerName(), null, 4, currentTestResourceDir);
}

From source file:org.apache.geode.internal.cache.IncrementalBackupDUnitTest.java

private void deleteMatching(File dir, final Pattern pattern) throws IOException {
    Collection<File> files = FileUtils.listFiles(dir, new RegexFileFilter(pattern),
            DirectoryFileFilter.DIRECTORY);
    for (File file : files) {
        Files.delete(file.toPath());
    }/*from   w  w w.j ava 2  s  .  c o m*/
}

From source file:com.streamsets.pipeline.stage.origin.logtail.TestFileTailSource.java

@Test
public void testFileDeletedBetweenRuns() throws Exception {
    File testDataDir = new File("target", UUID.randomUUID().toString());
    Assert.assertTrue(testDataDir.mkdirs());
    File file = new File(testDataDir, "file.txt-1");
    Files.write(file.toPath(), Arrays.asList("A", "B", "C"), StandardCharsets.UTF_8);

    FileInfo fileInfo = new FileInfo();
    fileInfo.fileFullPath = testDataDir.getAbsolutePath() + "/file.txt-${PATTERN}";
    fileInfo.fileRollMode = FileRollMode.PATTERN;
    fileInfo.firstFile = "";
    fileInfo.patternForToken = "[0-9]";
    Source source = createSourceForPeriodicFile(testDataDir.getAbsolutePath() + "/file.txt-${PATTERN}",
            "[0-9]");
    SourceRunner runner = createRunner(source);
    try {//  w  w  w .jav  a2 s  .  com
        // run till current end and stop pipeline
        runner.runInit();
        StageRunner.Output output = runner.runProduce(null, 10);
        Assert.assertEquals(3, output.getRecords().get("lane").size());
        runner.runDestroy();

        Files.delete(file.toPath());

        // run again, no new data, no error
        source = createSourceForPeriodicFile(testDataDir.getAbsolutePath() + "/file.txt-${PATTERN}", "[0-9]");
        runner = createRunner(source);
        runner.runInit();
        output = runner.runProduce(output.getNewOffset(), 10);
        Assert.assertEquals(0, output.getRecords().get("lane").size());
        runner.runDestroy();

        file = new File(testDataDir, "file.txt-2");
        Files.write(file.toPath(), Arrays.asList("A", "B"), StandardCharsets.UTF_8);

        // run again, new file
        source = createSourceForPeriodicFile(testDataDir.getAbsolutePath() + "/file.txt-${PATTERN}", "[0-9]");
        runner = createRunner(source);
        runner.runInit();
        output = runner.runProduce(output.getNewOffset(), 10);
        Assert.assertEquals(2, output.getRecords().get("lane").size());

    } finally {
        runner.runDestroy();
    }
}

From source file:com.streamsets.pipeline.stage.origin.logtail.TestFileTailSource.java

@Test
public void testFileDeletedWhileRunning() throws Exception {
    File testDataDir = new File("target", UUID.randomUUID().toString());
    Assert.assertTrue(testDataDir.mkdirs());
    File file = new File(testDataDir, "file.txt-1");
    Files.write(file.toPath(), Arrays.asList("A", "B", "C"), StandardCharsets.UTF_8);

    FileInfo fileInfo = new FileInfo();
    fileInfo.fileFullPath = testDataDir.getAbsolutePath() + "/file.txt-${PATTERN}";
    fileInfo.fileRollMode = FileRollMode.PATTERN;
    fileInfo.firstFile = "";
    fileInfo.patternForToken = "[0-9]";
    Source source = createSourceForPeriodicFile(testDataDir.getAbsolutePath() + "/file.txt-${PATTERN}",
            "[0-9]");
    SourceRunner runner = createRunner(source);
    try {//www .  j a v  a  2s.  c  o m
        // run till current end and stop pipeline
        runner.runInit();
        StageRunner.Output output = runner.runProduce(null, 10);
        Assert.assertEquals(3, output.getRecords().get("lane").size());

        Files.delete(file.toPath());

        output = runner.runProduce(output.getNewOffset(), 10);
        Assert.assertEquals(0, output.getRecords().get("lane").size());

        file = new File(testDataDir, "file.txt-2");
        Files.write(file.toPath(), Arrays.asList("A", "B"), StandardCharsets.UTF_8);

        output = runner.runProduce(output.getNewOffset(), 10);
        Assert.assertEquals(2, output.getRecords().get("lane").size());

    } finally {
        runner.runDestroy();
    }
}