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.kurento.test.services.KmsService.java

private void deleteFolderAndContent(Path folder) throws IOException {
    if (folder != null) {
        Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
            @Override/*  ww  w.  ja va  2 s  .c  om*/
            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:org.schedulesdirect.grabber.Grabber.java

private void removeExpiredSchedules(FileSystem vfs) throws IOException, JSONException {
    final int[] i = new int[] { 0 };
    final Path root = vfs.getPath("schedules");
    Files.walkFileTree(root, new FileVisitor<Path>() {

        @Override// w ww  .j  a  v a2 s  .  co  m
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            return !Files.isSameFile(dir, root) ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            try (InputStream ins = Files.newInputStream(file)) {
                JSONArray sched = Config.get().getObjectMapper()
                        .readValue(IOUtils.toString(ins, ZipEpgClient.ZIP_CHARSET.toString()), JSONObject.class)
                        .getJSONArray("programs");
                if (isScheduleExpired(sched)) {
                    Files.delete(file);
                    ++i[0];
                }
            }
            return FileVisitResult.CONTINUE;
        }

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

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            return FileVisitResult.CONTINUE;
        }

    });
    LOG.info(String.format("Removed %d expired schedule(s).", i[0]));
}

From source file:org.openecomp.sdc.asdctool.impl.DataMigration.java

/**
 * the method creates all the files and dir which holds them. in case the
 * files exist they will not be created again.
 * //from w w w.  java  2  s . co m
 * @param appConfigDir
 *            the base path under which the output dir will be created and
 *            the export result files the created filesa are named according
 *            to the name of the table into which it will be imported.
 * @param exportToEs
 *            if true all the export files will be recreated
 * @returnthe returns a map of tables and the files representing them them
 */
private Map<Table, File> createOutPutFiles(String appConfigDir, boolean exportToEs) {
    Map<Table, File> result = new EnumMap<Table, File>(Table.class);
    File outputDir = new File(appConfigDir + "/output/");
    if (!createOutPutFolder(outputDir)) {
        return null;
    }
    for (Table table : Table.values()) {
        File file = new File(outputDir + "/" + table.getTableDescription().getTableName());
        if (exportToEs) {
            try {
                if (file.exists()) {
                    Files.delete(file.toPath());
                }
            } catch (IOException e) {
                log.error("failed to delete output file " + file.getAbsolutePath(), e);
                return null;
            }
            file = new File(outputDir + "/" + table.getTableDescription().getTableName());
        }
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                log.error("failed to create output file " + file.getAbsolutePath(), e);
                return null;
            }
        }
        result.put(table, file);

    }
    return result;
}

From source file:de.blizzy.backup.backup.BackupRun.java

private void removeFiles(Set<FileEntry> files) {
    for (FileEntry file : files) {
        File f = Utils.toBackupFile(file.backupPath, settings.getOutputFolder());
        Path path = f.toPath();//w  ww .  ja  v  a2 s  .com
        try {
            Files.delete(path);
        } catch (IOException e) {
            BackupPlugin.getDefault().logError("error deleting file: " + file.backupPath, e); //$NON-NLS-1$
            fireBackupErrorOccurred(e, BackupErrorEvent.Severity.WARNING);
        }

        removeFoldersIfEmpty(f.getParentFile());

        database.factory().delete(Tables.FILES).where(Tables.FILES.ID.equal(Integer.valueOf(file.id)))
                .execute();
    }
}

From source file:de.blizzy.backup.backup.BackupRun.java

private void removeFoldersIfEmpty(File folder) {
    File outputFolder = new File(settings.getOutputFolder());
    if (Utils.isParent(new FileSystemFileOrFolder(outputFolder), new FileSystemFileOrFolder(folder))
            && (folder.list().length == 0)) {

        try {//w w w . j a  v  a2s  .c om
            BackupPlugin.getDefault().logMessage("deleting empty folder: " + folder.getAbsolutePath()); //$NON-NLS-1$
            Files.delete(folder.toPath());

            File parentFolder = folder.getParentFile();
            removeFoldersIfEmpty(parentFolder);
        } catch (IOException e) {
            BackupPlugin.getDefault().logError("error deleting folder: " + folder.getAbsolutePath(), e); //$NON-NLS-1$
            fireBackupErrorOccurred(e, BackupErrorEvent.Severity.WARNING);
        }
    }
}

From source file:org.schedulesdirect.grabber.Grabber.java

private void removeUnusedPrograms(FileSystem vfs) throws IOException {
    final int[] i = new int[] { 0 };
    final Path root = vfs.getPath("programs");
    Files.walkFileTree(root, new FileVisitor<Path>() {

        @Override/*from w w  w  .  j a  va2s  . c  o m*/
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            return !Files.isSameFile(root, dir) ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            String id = file.getName(file.getNameCount() - 1).toString();
            id = id.substring(0, id.indexOf('.'));
            if (!activeProgIds.contains(id)) {
                if (LOG.isDebugEnabled())
                    LOG.debug(String.format("CacheCleaner: Unused '%s'", id));
                Files.delete(file);
                ++i[0];
            }
            return FileVisitResult.CONTINUE;
        }

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

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            return FileVisitResult.CONTINUE;
        }

    });
    LOG.info(String.format("Removed %d unused program(s).", i[0]));
}

From source file:edu.utah.bmi.ibiomes.lite.IBIOMESLiteManager.java

/**
 * Remove existing XML and HTML files//from   ww w.  ja va  2  s. c o m
 * @throws Exception 
 */
public int cleanData() throws Exception {

    int nDelete = 0;
    if (this.outputToConsole)
        System.out.println("Removing experiments...");

    //remove main XML file
    Path indexXmlPath = Paths.get(publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_XML_INDEX);
    if (Files.exists(indexXmlPath, LinkOption.NOFOLLOW_LINKS))
        Files.delete(indexXmlPath);
    this.experimentListXml = new XmlExperimentListFile(
            publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_XML_INDEX);

    //remove main HTML file
    Path indexHtmlPath = Paths.get(publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_HTML_INDEX);
    if (Files.exists(indexHtmlPath, LinkOption.NOFOLLOW_LINKS))
        Files.delete(indexHtmlPath);

    //remove experiments data (XML, HTML, files)
    File htmlDir = new File(publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_EXPERIMENT_DIR);
    File[] htmlFiles = htmlDir.listFiles();
    for (int f = 0; f < htmlFiles.length; f++) {
        Utils.removeDirectoryRecursive(Paths.get(htmlFiles[f].getCanonicalPath()));
        nDelete++;
    }
    return nDelete;
}

From source file:org.schedulesdirect.grabber.Grabber.java

private void removeIgnoredStations(FileSystem vfs) throws IOException {
    final int[] i = new int[] { 0 };
    final Path root = vfs.getPath("schedules");
    Files.walkFileTree(root, new FileVisitor<Path>() {

        @Override//from   ww w  . jav  a  2  s. c o m
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            return !Files.isSameFile(root, dir) ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            String id = file.getName(file.getNameCount() - 1).toString();
            id = id.substring(0, id.indexOf('.'));
            if (stationList != null && !stationList.contains(id)) {
                if (LOG.isDebugEnabled())
                    LOG.debug(String.format("CacheCleaner: Remove '%s'", id));
                Files.delete(file);
                ++i[0];
            }
            return FileVisitResult.CONTINUE;
        }

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

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            return FileVisitResult.CONTINUE;
        }

    });
    LOG.info(String.format("Removed %d ignored station(s).", i[0]));
}

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

@Test
public void testTailFilesDeletion() throws Exception {
    File testDataDir = new File("target", UUID.randomUUID().toString());
    File testDataDir1 = new File(testDataDir, UUID.randomUUID().toString());
    File testDataDir2 = new File(testDataDir, UUID.randomUUID().toString());
    Assert.assertTrue(testDataDir1.mkdirs());
    Assert.assertTrue(testDataDir2.mkdirs());
    Path file1 = new File(testDataDir1, "log1.txt").toPath();
    Path file2 = new File(testDataDir2, "log2.txt").toPath();
    Files.write(file1, Arrays.asList("Hello"), UTF8);
    Files.write(file2, Arrays.asList("Hola"), UTF8);

    FileInfo fileInfo1 = new FileInfo();
    fileInfo1.fileFullPath = testDataDir.getAbsolutePath() + "/*/log*.txt";
    fileInfo1.fileRollMode = FileRollMode.REVERSE_COUNTER;
    fileInfo1.firstFile = "";
    fileInfo1.patternForToken = "";

    FileTailConfigBean conf = new FileTailConfigBean();
    conf.dataFormat = DataFormat.TEXT;/*from www .  j a va 2 s .  com*/
    conf.multiLineMainPattern = "";
    conf.batchSize = 25;
    conf.maxWaitTimeSecs = 1;
    conf.fileInfos = Arrays.asList(fileInfo1);
    conf.postProcessing = PostProcessingOptions.NONE;
    conf.dataFormatConfig.textMaxLineLen = 1024;

    FileTailSource source = new FileTailSource(conf, SCAN_INTERVAL);
    SourceRunner runner = new SourceRunner.Builder(FileTailDSource.class, source).addOutputLane("lane")
            .addOutputLane("metadata").build();
    try {
        runner.runInit();
        StageRunner.Output output = runner.runProduce(null, 10);
        output = runner.runProduce(output.getNewOffset(), 10);
        Assert.assertTrue(output.getNewOffset().contains("log1.txt"));
        Assert.assertTrue(output.getNewOffset().contains("log2.txt"));
        Files.delete(file1);
        Files.delete(testDataDir1.toPath());
        output = runner.runProduce(output.getNewOffset(), 10);
        output = runner.runProduce(output.getNewOffset(), 10);
        Assert.assertFalse(output.getNewOffset().contains("log1.txt"));
        Assert.assertTrue(output.getNewOffset().contains("log2.txt"));
    } finally {
        runner.runDestroy();
    }
}

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

@Test
public void partialObjectGetOverChunkBoundry() throws IOException, XmlProcessingException {
    final String bucketName = "partialGetOverBoundry";
    final String testFile = "testObject.txt";
    final Path filePath = Files.createTempFile("ds3", testFile);
    final int seed = 12345;
    LOG.info("Test file: " + filePath.toAbsolutePath());
    try {/*from   ww w  . j  a va 2s  . c o  m*/
        HELPERS.ensureBucketExists(bucketName, envDataPolicyId);

        final int objectSize = PutBulkJobSpectraS3Request.MIN_UPLOAD_SIZE_IN_BYTES * 2;

        final List<Ds3Object> objs = Lists.newArrayList(new Ds3Object(testFile, objectSize));

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

        putJob.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() {
            @Override
            public SeekableByteChannel buildChannel(final String key) throws IOException {
                final byte[] randomData = IOUtils.toByteArray(new RandomDataInputStream(seed, objectSize));
                final ByteBuffer randomBuffer = ByteBuffer.wrap(randomData);

                final ByteArraySeekableByteChannel channel = new ByteArraySeekableByteChannel(objectSize);
                channel.write(randomBuffer);

                return channel;

            }
        });

        final List<Ds3Object> partialObjectGet = Lists.newArrayList();
        partialObjectGet.add(new PartialDs3Object(testFile,
                Range.byPosition(PutBulkJobSpectraS3Request.MIN_UPLOAD_SIZE_IN_BYTES - 100,
                        PutBulkJobSpectraS3Request.MIN_UPLOAD_SIZE_IN_BYTES + 99)));

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

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

        assertThat(Files.size(filePath), is(200L));

    } finally {
        Files.delete(filePath);
        deleteAllContents(client, bucketName);
    }
}