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:gov.vha.isaac.rf2.filter.RF2Filter.java

private void handleFile(Path inputFile, Path outputFile) throws IOException {
    boolean justCopy = true;
    boolean justSkip = false;

    if (inputFile.toFile().getName().toLowerCase().endsWith(".txt")) {
        justCopy = false;/* w w  w  . jav a 2s.  co m*/
        //Filter the file
        BufferedReader fileReader = new BufferedReader(
                new InputStreamReader(new BOMInputStream(new FileInputStream(inputFile.toFile())), "UTF-8"));
        BufferedWriter fileWriter = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(outputFile.toFile()), "UTF-8"));
        PipedOutputStream pos = new PipedOutputStream();
        PipedInputStream pis = new PipedInputStream(pos);
        CSVReader csvReader = new CSVReader(new InputStreamReader(pis), '\t', CSVParser.NULL_CHARACTER); //don't look for quotes, the data is bad, and has floating instances of '"' all by itself

        boolean firstLine = true;
        String line = null;
        long kept = 0;
        long skipped = 0;
        long total = 0;

        int moduleColumn = -1;

        while ((line = fileReader.readLine()) != null) {
            total++;
            //Write this line into the CSV parser
            pos.write(line.getBytes());
            pos.write("\r\n".getBytes());
            pos.flush();
            String[] fields = csvReader.readNext();

            boolean correctModule = false;
            for (String ms : moduleStrings_) {
                if (moduleColumn >= 0 && fields[moduleColumn].equals(ms)) {
                    correctModule = true;
                    break;
                }
            }

            if (firstLine || correctModule) {
                kept++;
                fileWriter.write(line);
                fileWriter.write("\r\n");
            } else {
                //don't write line
                skipped++;
            }

            if (firstLine) {

                log("Filtering file " + inputDirectory.toPath().relativize(inputFile).toString());
                firstLine = false;
                if (fields.length < 2) {
                    log("txt file doesn't look like a data file - abort and just copy.");
                    justCopy = true;
                    break;
                }
                for (int i = 0; i < fields.length; i++) {
                    if (fields[i].equals("moduleId")) {
                        moduleColumn = i;
                        break;
                    }
                }
                if (moduleColumn < 0) {
                    log("No moduleId column found - skipping file");
                    justSkip = true;
                    break;
                }
            }
        }

        fileReader.close();
        csvReader.close();
        fileWriter.close();

        if (!justCopy) {
            log("Kept " + kept + " Skipped " + skipped + " out of " + total + " lines in "
                    + inputDirectory.toPath().relativize(inputFile).toString());
        }
    }

    if (justCopy) {
        //Just copy the file
        Files.copy(inputFile, outputFile, StandardCopyOption.REPLACE_EXISTING);
        log("Copied file " + inputDirectory.toPath().relativize(inputFile).toString());
    }

    if (justSkip) {
        Files.delete(outputFile);
        log("Skipped file " + inputDirectory.toPath().relativize(inputFile).toString()
                + " because it doesn't contain a moduleId");
    }
}

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

/**
 * Deletes the specified file.//from   w w w  .j  av  a 2s.  c  o m
 * Throws an {@link UtilException} if the deletion fails.
 * @param path the path of the file to delete.
 */
public static void deleteFile(final String path) {
    try {
        Files.delete(Paths.get(path));
    } catch (IOException e) {
        throw new UtilException(e);
    }
}

From source file:org.ulyssis.ipp.reader.Reader.java

/**
 * Perform cleanup on shutdown. (When the thread is interrupted.)
 *//*  w w  w.  jav a2s . c o m*/
private void shutdownHook() {
    statusReporter.broadcast(new StatusMessage(StatusMessage.MessageType.SHUTDOWN,
            String.format("Shutting down reader %s.", options.getId())));
    if (speedwayInitialized) {
        LOG.info("Shutting down reader!");
        boolean successfulStop = llrpReader.stop();
        if (!successfulStop) {
            LOG.error("Could not stop the Speedway!");
        } else {
            LOG.info("Successfully stopped the reader!");
        }
    }
    replayChannel.ifPresent(channel -> {
        final Path replayFile = options.getReplayFile().get();
        try {
            channel.close();
        } catch (IOException e) {
            LOG.error("Error while closing replay log file: {}.", replayFile, e);
        }
        try {
            if (Files.size(replayFile) == 0L) {
                LOG.info("Deleting empty replay file: {}", replayFile);
                Files.delete(replayFile);
            }
        } catch (IOException e) {
            LOG.error("Couldn't check size of replay log {}, or delete it.", replayFile, e);
        }
    });
    LOG.info("Bye bye!");
}

From source file:com.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java

/**
 * ????.//  w  ww.j  ava2s  .c o  m
 * 
 * @param metadata ?urlTree
 * @param ctx urlTree
 */
@Override
public void rmdir(UrlTreeMetaData<InputStream> metadata, UrlTreeContext ctx)
        throws BadContentException, FileNotFoundException {
    Path f = generateFileObj(metadata.getAbsolutePath());
    logger.debug("called rmdir: " + f.getFileName());
    if (!Files.exists(f)) {
        throw new FileNotFoundException("file not exists");
    }

    try {
        Files.delete(f);
    } catch (IOException e) {
        logger.error("rmdir failure", e);
        throw new RuntimeException(e);
    }
}

From source file:majordodo.task.BrokerTestUtils.java

@After
public void brokerTestUtilsAfter() throws Exception {
    if (startBroker) {
        server.close();/*from ww w.ja v a  2 s .c  o  m*/
        broker.close();
        server = null;
        broker = null;
    }
    if (startReplicatedBrokers) {
        brokerLocator.close();
        server2.close();
        broker2.close();
        server1.close();
        broker1.close();
        zkServer.close();
        brokerLocator = null;
        server2 = null;
        broker2 = null;
        server1 = null;
        broker1 = null;
        zkServer = null;
    }

    // Resetting brokers config
    if (startBroker) {
        brokerConfig = new BrokerConfiguration();
    }
    if (startReplicatedBrokers) {
        broker1Config = new BrokerConfiguration();
        broker2Config = new BrokerConfiguration();
    }

    if (workDir != null) {
        Files.walkFileTree(workDir, new FileVisitor<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;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return FileVisitResult.CONTINUE;
            }

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

        });
    }

    if (!ignoreUnhandledExceptions && !unhandledExceptions.isEmpty()) {
        System.out.println("Errors occurred during excecution:");
        for (Throwable e : unhandledExceptions) {
            System.out.println("\n" + ExceptionUtils.getStackTrace(e) + "\n");
        }
        fail("There are " + unhandledExceptions.size() + " unhandled exceptions!");
    }
}

From source file:org.neo4j.io.fs.FileUtils.java

private static void deleteFileWithRetries(Path file, int tries) throws IOException {
    try {//  ww w  .ja  v  a2s  .co  m
        Files.delete(file);
    } catch (IOException e) {
        if (SystemUtils.IS_OS_WINDOWS && mayBeWindowsMemoryMappedFileReleaseProblem(e)) {
            if (tries >= WINDOWS_RETRY_COUNT) {
                throw new MaybeWindowsMemoryMappedFileReleaseProblem(e);
            }
            waitAndThenTriggerGC();
            deleteFileWithRetries(file, tries + 1);
        } else {
            throw e;
        }
    }
}

From source file:ee.ria.xroad.confproxy.ConfProxyProperties.java

/**
 * Deletes the certificate file for the given key id.
 * @param keyId the id for the key corresponding to the certificate
 * @throws IOException if an I/O error occurs
 *///from   ww  w . j a v a2 s . c om
public final void deleteCert(final String keyId) throws IOException {
    Files.delete(getCertPath(keyId));
}

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

public void testAddedFieldIndexableAndQueryable() throws Exception {
    assertSchemaResource(collection, "managed-schema");
    deleteCore();/*w ww.  j a v  a2s .  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());

    assertTrue(managedSchemaFile.exists());
    String managedSchemaContents = FileUtils.readFileToString(managedSchemaFile, "UTF-8");
    assertFalse(managedSchemaContents.contains("\"new_field\""));

    clearIndex();

    String errString = "unknown field 'new_field'";
    ignoreException(Pattern.quote(errString));
    try {
        assertU(adoc("new_field", "thing1 thing2", "str", "X"));
        fail();
    } 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();
    }
    assertU(commit());
    assertQ(req("new_field:thing1"), "//*[@numFound='0']");

    Map<String, Object> options = new HashMap<>();
    options.put("stored", "false");
    IndexSchema oldSchema = h.getCore().getLatestSchema();
    String fieldName = "new_field";
    String fieldType = "text";
    SchemaField newField = oldSchema.newField(fieldName, fieldType, options);
    IndexSchema newSchema = oldSchema.addField(newField);
    h.getCore().setLatestSchema(newSchema);

    assertU(adoc("new_field", "thing1 thing2", "str", "X"));
    assertU(commit());

    assertQ(req("new_field:thing1"), "//*[@numFound='1']");
}

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

@Test
public void getMimeTypeMissing() throws Exception {
    try (Bundle bundle = Bundles.createBundle()) {
        Path mimetypePath = bundle.getRoot().resolve("mimetype");
        Files.delete(mimetypePath);
        // Fall back according to our spec
        assertEquals("application/vnd.wf4ever.robundle+zip", Bundles.getMimeType(bundle));
    }/*from www. ja  v a  2s  . com*/
}

From source file:de.ingrid.interfaces.csw.cache.AbstractFileCache.java

@Override
public void commitTransaction() throws IOException {
    if (!this.isInitialized()) {
        this.initialize();
    }//www.j a v  a  2  s.  com
    if (this.isInTransaction()) {
        // move content of this instance to the original cache
        Path originalDirPath = this.getCachePath().toPath();
        File tmpDir = new File(this.getTempPath().getAbsolutePath() + "_tmp");
        // make sure all parent paths are created
        tmpDir.mkdirs();
        // then remove the last directory
        Files.delete(tmpDir.toPath());
        Path workDirPath = this.getWorkPath().toPath();
        if (log.isInfoEnabled()) {
            log.info("Rename old cache: " + originalDirPath + " to " + tmpDir.toPath());
        }
        FileUtils.waitAndMove(originalDirPath, tmpDir.toPath(),
                ApplicationProperties.getInteger(ConfigurationKeys.FILE_OPERATION_TIMEOUT, 10000));
        if (log.isInfoEnabled()) {
            log.info("Rename new cache: " + workDirPath + " to " + originalDirPath);
        }
        FileUtils.waitAndMove(workDirPath, originalDirPath,
                ApplicationProperties.getInteger(ConfigurationKeys.FILE_OPERATION_TIMEOUT, 10000));
        if (log.isInfoEnabled()) {
            log.info("Remove tmp path: " + tmpDir.toPath());
        }
        FileUtils.waitAndDelete(tmpDir.toPath(),
                ApplicationProperties.getInteger(ConfigurationKeys.FILE_OPERATION_TIMEOUT, 10000));

        this.inTransaction = false;
    } else {
        throw new RuntimeException("The cache is not in transaction mode.");
    }
}