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.apache.hyracks.storage.am.lsm.common.impls.AbstractLSMIndexFileManager.java

@Override
public void recoverTransaction() throws HyracksDataException {
    String[] files = listDirFiles(baseDir, transactionFileNameFilter);
    File dir = new File(baseDir);
    try {/*from   w w  w . j  a  v  a 2s . c o m*/
        if (files.length == 0) {
            // Do nothing
        } else if (files.length > 1) {
            throw new HyracksDataException("Found more than one transaction");
        } else {
            Files.delete(Paths.get(dir.getPath() + File.separator + files[0]));
        }
    } catch (IOException e) {
        throw new HyracksDataException("Failed to recover transaction", e);
    }
}

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

public void testAddFieldWhenItAlreadyExists() throws Exception {
    deleteCore();/*from w w  w  .  j  a v a 2 s  .c  o  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());

    assertNotNull("Field 'str' is not present in the schema",
            h.getCore().getLatestSchema().getFieldOrNull("str"));

    String errString = "Field 'str' already exists.";
    ignoreException(Pattern.quote(errString));
    try {
        Map<String, Object> options = new HashMap<>();
        IndexSchema oldSchema = h.getCore().getLatestSchema();
        String fieldName = "str";
        String fieldType = "string";
        SchemaField newField = oldSchema.newField(fieldName, fieldType, options);
        IndexSchema newSchema = oldSchema.addField(newField);
        h.getCore().setLatestSchema(newSchema);
        fail("Should fail when adding a field that already exists");
    } catch (Exception e) {
        for (Throwable t = e; t != null; t = t.getCause()) {
            // short circuit out if we found what we expected
            if (t.getMessage() != null && -1 != t.getMessage().indexOf(errString))
                return;
        }
        // otherwise, rethrow it, possibly completely unrelated
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                "Unexpected error, expected error matching: " + errString, e);
    } finally {
        resetExceptionIgnores();
    }
}

From source file:org.hawkular.inventory.impl.tinkerpop.test.BasicTest.java

private static void deleteGraph() throws Exception {
    Path path = Paths.get("./", "__tinker.graph");

    if (!path.toFile().exists()) {
        return;//ww w .java  2  s.c  o m
    }

    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;
        }
    });
}

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

@Override
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public void delete(String identifier) throws BinaryStoreServiceException, DataNotFoundException {
    Path path = getPathForIdentifier(identifier);
    if (!Files.exists(path)) {
        throw new DataNotFoundException("Unable to find an object with id [" + identifier + "] in the storage");
    }/*from ww w .java  2 s  .c o m*/
    try {
        Files.delete(path);
    } catch (Exception e) {
        throw new BinaryStoreServiceException(e);
    }
}

From source file:fr.gael.dhus.sync.impl.ODataProductSynchronizer.java

/**
 * Uses the given `http_client` to download `url` into `out_tmp`.
 * Renames `out_tmp` to the value of the filename param of the Content-Disposition header field.
 * Returns a path to the renamed file./*w  w  w  .  j  ava2s  .  c o  m*/
 *
 * @param http_client synchronous interruptible HTTP client.
 * @param out_tmp download destination file on disk (will be created if does not exist).
 * @param url what to download.
 * @return Path to file with its actual name.
 * @throws IOException Anything went wrong (with IO or network, or if the HTTP header field
 *       Content-Disposition is missing).
 * @throws InterruptedException Thread has been interrupted.
 */
private DownloadResult downloadValidateRename(InterruptibleHttpClient http_client, Path out_tmp, String url)
        throws IOException, InterruptedException {
    try (FileChannel output = FileChannel.open(out_tmp, StandardOpenOption.CREATE_NEW,
            StandardOpenOption.WRITE)) {

        HttpResponse response = http_client.interruptibleGet(url, output);

        // If the response's status code is not 200, something wrong happened
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            Formatter ff = new Formatter();
            ff.format(
                    "Synchronizer#%d cannot download product at %s,"
                            + " remote dhus returned message '%s' (HTTP%d)",
                    getId(), url, response.getStatusLine().getReasonPhrase(),
                    response.getStatusLine().getStatusCode());
            throw new IOException(ff.out().toString());
        }

        // Gets the filename from the HTTP header field `Content-Disposition'
        Pattern pat = Pattern.compile("filename=\"(.+?)\"", Pattern.CASE_INSENSITIVE);
        String contdis = response.getFirstHeader("Content-Disposition").getValue();
        Matcher m = pat.matcher(contdis);
        if (!m.find()) {
            throw new IOException("Synchronizer#" + getId()
                    + " Missing HTTP header field `Content-Disposition` that determines the filename");
        }
        String filename = m.group(1);
        if (filename == null || filename.isEmpty()) {
            throw new IOException(
                    "Synchronizer#" + getId() + " Invalid filename in HTTP header field `Content-Disposition`");
        }

        // Renames the downloaded file
        output.close();
        Path dest = out_tmp.getParent().resolve(filename);
        Files.move(out_tmp, dest, StandardCopyOption.ATOMIC_MOVE);

        DownloadResult res = new DownloadResult(dest, response.getEntity().getContentType().getValue(),
                response.getEntity().getContentLength());

        return res;
    } finally {
        if (Files.exists(out_tmp)) {
            Files.delete(out_tmp);
        }
    }
}

From source file:org.silverpeas.core.util.file.FileUtil.java

public static boolean deleteEmptyDir(File directory) {
    if (directory.exists() && directory.isDirectory() && directory.list() != null
            && directory.list().length == 0) {
        try {/*from   w  w w . j a v a 2  s. c o m*/
            Files.delete(directory.toPath());
            return true;
        } catch (IOException e) {
            SilverLogger.getLogger(FileUtil.class).warn(e);
            return false;
        }
    }
    return false;
}

From source file:org.fim.internal.hash.FileHasherTest.java

private Path createFileWithSize(int fileSize) throws IOException {
    Path newFile = context.getRepositoryRootDir().resolve("file_" + fileSize);
    if (Files.exists(newFile)) {
        Files.delete(newFile);
    }/*from w w  w.  j  a va2s .  co  m*/

    if (fileSize == 0) {
        Files.createFile(newFile);
        return newFile;
    }

    try (ByteArrayOutputStream out = new ByteArrayOutputStream(fileSize)) {
        int contentSize = _1_KB / 4;
        int remaining = fileSize;
        for (; remaining > 0; globalSequenceCount++) {
            int size = min(contentSize, remaining);
            byte[] content = generateContent(globalSequenceCount, size);
            remaining -= size;
            out.write(content);
        }

        byte[] fileContent = out.toByteArray();
        assertThat(fileContent.length).isEqualTo(fileSize);
        Files.write(newFile, fileContent, CREATE);
    }

    return newFile;
}

From source file:com.radiohitwave.ftpsync.API.java

public void DeleteNonExistingFiles(String localBasePath) {
    Log.info("Searching for non-existing Files");
    String[] remoteFiles = this.GetRemoteFileList();
    final String finalLocalPath = this.RemoveTrailingSlash(localBasePath);
    AtomicInteger logDeletedFiles = new AtomicInteger();

    try {/*from   w  w w  . j a  va2  s .  com*/
        Files.walk(Paths.get(localBasePath)).forEach(filePath -> {
            if (Files.isRegularFile(filePath)) {
                String file = filePath.toString().replace(finalLocalPath, "");
                file = file.substring(1);
                file = file.replace("\\", "/");
                if (Arrays.binarySearch(remoteFiles, file) < 0) {
                    try {
                        Log.info("Deleting <" + file + ">");
                        Files.delete(filePath);
                        logDeletedFiles.incrementAndGet();
                    } catch (IOException ex) {
                        Log.error("Cant delete File:" + ex.toString());
                        Log.remoteError(ex);
                    }
                }
            }
        });
        Files.walk(Paths.get(localBasePath)).forEach(filePath -> {
            if (Files.isDirectory(filePath)) {
                String file = filePath.toString().replace(finalLocalPath + "/", "");
                try {
                    Files.delete(filePath);
                    Log.info("Deleting empty Directory <" + file + ">");
                } catch (IOException e) {

                }
            }
        });
    } catch (IOException ex) {
        Log.error(ex.toString());
    }
    Log.info("Disk-Cleanup finished, deleted " + logDeletedFiles.get() + " Files");
    if (logDeletedFiles.get() > this.nonExistingFilesThreesholdBeforeAlert) {
        Log.remoteInfo("Deleted " + logDeletedFiles.get() + " non-existing Files");
    }

}

From source file:org.apache.openaz.xacml.pdp.test.TestBase.java

/**
 * Removes all the Response* files from the results directory.
 *//*from  www  . j  ava2s.  c  o  m*/
public void removeResults() {
    try {
        //
        // Determine where the results are supposed to be written to
        //
        Path resultsPath;
        if (this.output != null) {
            resultsPath = this.output;
        } else {
            resultsPath = Paths.get(this.directory.toString(), "results");
        }
        //
        // Walk the files
        //
        Files.walkFileTree(resultsPath, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.getFileName().toString().startsWith("Response")) {
                    Files.delete(file);
                }
                return super.visitFile(file, attrs);
            }
        });
    } catch (IOException e) {
        logger.error("Failed to removeRequests from " + this.directory + " " + e);
    }
}

From source file:org.cryptomator.cryptofs.CryptoFileSystemImpl.java

void createDirectory(CryptoPath cleartextDir, FileAttribute<?>... attrs) throws IOException {
    CryptoPath cleartextParentDir = cleartextDir.getParent();
    if (cleartextParentDir == null) {
        return;/*from  w  w w  .  ja  v  a2  s . c o  m*/
    }
    Path ciphertextParentDir = cryptoPathMapper.getCiphertextDirPath(cleartextParentDir);
    if (!Files.exists(ciphertextParentDir)) {
        throw new NoSuchFileException(cleartextParentDir.toString());
    }
    Path ciphertextFile = cryptoPathMapper.getCiphertextFilePath(cleartextDir, CiphertextFileType.FILE);
    if (Files.exists(ciphertextFile)) {
        throw new FileAlreadyExistsException(cleartextDir.toString());
    }
    Path ciphertextDirFile = cryptoPathMapper.getCiphertextFilePath(cleartextDir, CiphertextFileType.DIRECTORY);
    boolean success = false;
    try {
        Directory ciphertextDir = cryptoPathMapper.getCiphertextDir(cleartextDir);
        try (FileChannel channel = FileChannel.open(ciphertextDirFile,
                EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE), attrs)) {
            channel.write(ByteBuffer.wrap(ciphertextDir.dirId.getBytes(UTF_8)));
        }
        Files.createDirectories(ciphertextDir.path);
        success = true;
    } finally {
        if (!success) {
            Files.delete(ciphertextDirFile);
            dirIdProvider.delete(ciphertextDirFile);
        }
    }
}