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:com.clust4j.algo.pipeline.PipelineTest.java

@Test
public void testSupervisedVarArgs() throws ClassNotFoundException, FileNotFoundException, IOException {
    final double[][] data = new double[][] { new double[] { 0.005, 0.182751, 0.1284 },
            new double[] { 3.65816, 0.29518, 2.123316 }, new double[] { 4.1234, 0.27395, 1.8900002 } };

    final Array2DRowRealMatrix mat = new Array2DRowRealMatrix(data);
    final NearestCentroidParameters planner = new NearestCentroidParameters().setVerbose(true);

    // Build the pipeline
    final SupervisedPipeline<NearestCentroid> pipe = new SupervisedPipeline<NearestCentroid>(planner,
            new StandardScaler());
    final NearestCentroid nc = pipe.fit(mat, new int[] { 0, 1, 1 });

    assertTrue(nc.getLabels()[0] == 0 && nc.getLabels()[1] == 1);
    assertTrue(nc.getLabels()[1] == nc.getLabels()[2]);
    System.out.println();//from w  w  w  .j a  v a  2 s.  c  o  m

    pipe.saveObject(new FileOutputStream(TestSuite.tmpSerPath));
    assertTrue(TestSuite.file.exists());

    @SuppressWarnings("unchecked")
    SupervisedPipeline<NearestCentroid> pipe2 = (SupervisedPipeline<NearestCentroid>) SupervisedPipeline
            .loadObject(new FileInputStream(TestSuite.tmpSerPath));

    final NearestCentroid nc2 = (NearestCentroid) pipe2.fit(mat, new int[] { 0, 1, 1 });

    assertTrue(nc2.getLabels()[0] == 0 && nc2.getLabels()[1] == 1);
    assertTrue(nc2.getLabels()[1] == nc2.getLabels()[2]);

    Files.delete(TestSuite.path);
}

From source file:ru.codemine.ccms.sales.domino.DominoSalesLoader.java

private Map<LocalDate, Map<String, Sales>> getSalesMap() {
    File path = new File(settingsService.getStorageEmailPath());
    FilenameFilter filter = new EndsWithFilenameFilter(".xls", EndsWithFilenameFilter.NEVER);
    Map<LocalDate, Map<String, Sales>> result = new HashMap();
    for (File file : path.listFiles(filter)) {
        try {//from   ww w  . j  a v  a2s . c  o  m

            log.info(" : " + file.getName());

            FileInputStream fs = new FileInputStream(file);
            HSSFWorkbook workbook = new HSSFWorkbook(fs);
            HSSFSheet sheet = workbook.getSheetAt(0);
            boolean dateFound = false;
            boolean colFound = false;
            Integer colNumber = 0;
            LocalDate fileDate = null;
            Map<String, Sales> parsedFileMap = new HashMap();

            for (Row row : sheet) {
                Cell firstCell = row.getCell(0);

                //
                // ?  
                //
                if (firstCell.getCellType() == Cell.CELL_TYPE_STRING && firstCell.getStringCellValue()
                        .startsWith("    ")) {
                    String bothDatesStr = firstCell.getStringCellValue()
                            .replace("     ? ", "");
                    String[] datesStr = bothDatesStr.split("  ");
                    DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.YYYY");
                    LocalDate startDate = formatter.parseLocalDate(datesStr[0]);
                    LocalDate endDate = formatter.parseLocalDate(datesStr[1]);
                    if (startDate != null && startDate.isEqual(endDate)) {
                        dateFound = true;
                        fileDate = startDate;
                        log.info(" : " + fileDate);
                    }

                }

                //
                // ? ? ? ? ?
                //

                else if (firstCell.getCellType() == Cell.CELL_TYPE_STRING
                        && firstCell.getStringCellValue().startsWith(" /")) {
                    for (Cell headersCell : row) {
                        if (headersCell.getCellType() == Cell.CELL_TYPE_STRING && headersCell
                                .getStringCellValue().startsWith(" ??")) {
                            colFound = true;
                            colNumber = headersCell.getColumnIndex();
                            log.info(" : " + colNumber);
                        }
                    }
                }

                //
                // ?   ? 
                //

                else if (dateFound && colFound && firstCell.getCellType() == Cell.CELL_TYPE_STRING
                        && firstCell.getStringCellValue().startsWith(":")) {
                    Sales sale = new Sales();

                    // ?  
                    String namesStr = firstCell.getStringCellValue().replace(": ",
                            "");
                    String delimiter = " - ";
                    if (namesStr.indexOf(delimiter) > 0
                            && namesStr.indexOf(delimiter) != namesStr.lastIndexOf(delimiter)) {
                        String name = namesStr.substring(namesStr.indexOf(delimiter) + delimiter.length(),
                                namesStr.lastIndexOf(delimiter));

                        //  ? 
                        boolean shopFinished = false;
                        int rcrd = 1;
                        int cashb_rcrd = 0;
                        while (!shopFinished) {
                            Row r = sheet.getRow(row.getRowNum() + rcrd);
                            if (r.getCell(0).getCellType() == Cell.CELL_TYPE_NUMERIC) // ? ?   
                            {
                                Double val = r.getCell(colNumber).getNumericCellValue();
                                //log.debug("i is: " + i + ", val is: " + val);
                                if (val > 0)
                                    sale.setValue(sale.getValue() + val); //
                                else {
                                    sale.setCashback(sale.getCashback() - val); //
                                    cashb_rcrd++;
                                }
                            } else if (r.getCell(0).getStringCellValue().startsWith(" :")) {
                                //log.debug("finished shop record, i is: " + i);
                                sale.setChequeCount(rcrd - cashb_rcrd - 1);
                                shopFinished = true;
                            }

                            rcrd++;
                        }

                        parsedFileMap.put(name, sale);
                        //Double value = row.getCell(colNumber).getNumericCellValue();
                        //parsedFileMap.put(name, value);
                        //log.debug("Recieved file map: " + parsedFileMap);
                    }

                }

            } // foreach row in sheet

            if (dateFound && colFound) {
                result.put(fileDate, parsedFileMap);
                log.info("...ok");
                Files.delete(file.toPath());
            } else {
                if (!dateFound) {
                    log.warn("     " + file.getName());
                }
                if (!colFound) {
                    log.warn(" ?      "
                            + file.getName());
                }
                log.error("?   " + file.getName());
            }

        } catch (Exception e) {
            //e.printStackTrace();
            log.error("?  ,  : "
                    + e.getMessage());
        }

    } // foreach file in path

    return result;
}

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

@Test
public void createBundlePath() throws Exception {
    Path source = Files.createTempFile("test", ".zip");
    source.toFile().deleteOnExit();//from w  w  w.j a  va2 s  .c  o m
    Files.delete(source);
    try (Bundle bundle = Bundles.createBundle(source)) {
        assertTrue(Files.isDirectory(bundle.getRoot()));
        assertEquals(source, bundle.getSource());
        assertTrue(Files.exists(source));
    }
    // As it was a specific path, it should NOT be deleted on close
    assertTrue(Files.exists(source));
}

From source file:com.netflix.nicobar.core.persistence.JarArchiveRepository.java

@Override
public void deleteArchive(ModuleId moduleId) throws IOException {
    Path moduleJar = getModuleJarPath(moduleId);
    if (Files.exists(moduleJar)) {
        Files.delete(moduleJar);
    }//from  w w  w .j  a va  2  s  . co  m
}

From source file:org.jboss.as.test.integration.logging.operations.CustomFormattersTestCase.java

@Test
public void testUsage() throws Exception {

    // Create the custom formatter
    CompositeOperationBuilder builder = CompositeOperationBuilder.create();
    ModelNode op = Operations.createAddOperation(CUSTOM_FORMATTER_ADDRESS);
    op.get("class").set("java.util.logging.XMLFormatter");
    // the module doesn't really matter since it's a JDK, so we'll just use the jboss-logmanager.
    op.get("module").set("org.jboss.logmanager");
    builder.addStep(op);/* ww w  . j a  v a  2  s.  com*/

    // Create the handler
    op = Operations.createAddOperation(HANDLER_ADDRESS);
    final ModelNode file = op.get("file");
    file.get("relative-to").set("jboss.server.log.dir");
    file.get("path").set(FILE_NAME);
    op.get("append").set(false);
    op.get("autoflush").set(true);
    op.get("named-formatter").set(CUSTOM_FORMATTER_NAME);
    builder.addStep(op);

    // Add the handler to the root logger
    op = Operations.createOperation("add-handler", ROOT_LOGGER_ADDRESS);
    op.get(ModelDescriptionConstants.NAME).set(HANDLER_NAME);
    builder.addStep(op);

    executeOperation(builder.build());

    // Get the log file
    op = Operations.createOperation("resolve-path", HANDLER_ADDRESS);
    ModelNode result = executeOperation(op);
    final Path logFile = Paths.get(Operations.readResult(result).asString());

    // The file should exist
    Assert.assertTrue("The log file was not created.", Files.exists(logFile));

    // Log 5 records
    doLog("Test message: ", 5);

    // Read the log file
    try (BufferedReader reader = Files.newBufferedReader(logFile, StandardCharsets.UTF_8)) {
        final Pattern pattern = Pattern.compile("^(<message>)+(Test message: \\d)+(</message>)$");
        final List<String> messages = new ArrayList<>(5);
        String line;
        while ((line = reader.readLine()) != null) {
            final String trimmedLine = line.trim();
            final Matcher m = pattern.matcher(trimmedLine);
            // Very simple xml parsing
            if (m.matches()) {
                messages.add(m.group(2));
            }
        }

        // Should be 5 messages
        Assert.assertEquals(5, messages.size());
        // Check each message
        int count = 0;
        for (String msg : messages) {
            Assert.assertEquals("Test message: " + count++, msg);
        }
    }

    builder = CompositeOperationBuilder.create();
    // Remove the handler from the root-logger
    op = Operations.createOperation("remove-handler", ROOT_LOGGER_ADDRESS);
    op.get(ModelDescriptionConstants.NAME).set(HANDLER_NAME);
    builder.addStep(op);

    // Remove the custom formatter
    op = Operations.createRemoveOperation(CUSTOM_FORMATTER_ADDRESS);
    builder.addStep(op);

    // Remove the handler
    op = Operations.createRemoveOperation(HANDLER_ADDRESS);
    builder.addStep(op);

    executeOperation(builder.build());

    // So we don't pollute other, verify the formatter and handler have been removed
    op = Operations.createReadAttributeOperation(ROOT_LOGGER_ADDRESS, "handlers");
    result = executeOperation(op);
    // Should be a list type
    final List<ModelNode> handlers = Operations.readResult(result).asList();
    for (ModelNode handler : handlers) {
        Assert.assertNotEquals(CUSTOM_FORMATTER_NAME, handler.asString());
    }
    verifyRemoved(CUSTOM_FORMATTER_ADDRESS);
    verifyRemoved(HANDLER_ADDRESS);

    // Delete the log file
    Files.delete(logFile);
    // Ensure it's been deleted
    Assert.assertFalse(Files.exists(logFile));
}

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

/**
 * Test method for {@link org.carcv.impl.core.io.FFMPEGVideoHandler#splitIntoFrames(java.nio.file.Path)}.
 *
 * @throws IOException/*from   ww  w  .j  a va2s. c  o m*/
 */
@Test
public void testSplitIntoFramesPath() throws IOException {
    FFMPEGVideoHandler fvh = new FFMPEGVideoHandler();
    FFMPEGVideoHandler.copyCarImagesToDir(entry.getCarImages(), videoDir);
    Path video = fvh.generateVideo(videoDir, FFMPEGVideoHandler.defaultFrameRate);

    assertTrue("Split failed.", FFMPEGVideoHandler.splitIntoFrames(video));

    Path dir = Paths.get(video.toString() + ".dir");
    DirectoryStream<Path> paths = Files.newDirectoryStream(dir);
    int counter = 0;
    for (@SuppressWarnings("unused")
    Path p : paths) {
        counter++;
    }
    assertEquals(entry.getCarImages().size(), counter);

    Files.delete(video);
    DirectoryWatcher.deleteDirectory(dir);
}

From source file:org.fao.geonet.api.cssstyle.CssStyleSettingsService.java

/**
 * Initialize less file in data folder.//from   w  ww  .  j  a v  a  2  s  .  c om
 *
 * @param path the path
 * @return the path
 * @throws IOException Signals that an I/O exception has occurred.
 */

private Path initializeLessFileInDataFolder(String path) throws IOException {
    final Path lessPath = Paths.get(path + "/gn_dynamic_style.json");
    try {
        Files.createFile(lessPath);
    } catch (final FileAlreadyExistsException e1) {
        Files.delete(lessPath);
        Files.createFile(lessPath);
    } catch (final NoSuchFileException e2) {
        final Path tmp = lessPath.getParent();
        Files.createDirectories(tmp);
        Files.createFile(lessPath);
    }
    return lessPath;
}

From source file:com.juancarlosroot.threads.SimulatedUser.java

private void deleteFolder(String folderName) {
    Path currentRelativePath = Paths.get("");
    String s = currentRelativePath.toAbsolutePath().toString();

    Path folderPath = Paths.get(s + "/" + folderName);

    try {//  w w w. j a  va2s .co m
        Files.delete(folderPath);
        System.out.println("Carpeta eliminada : " + s + "/" + folderName);
    } catch (IOException ex) {
        Logger.getLogger(SimulatedUser.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Error al eliminar carpeta : " + s + "/" + folderName);
    }
}

From source file:org.knime.ext.textprocessing.data.StanfordNERModelPortObject.java

/**
 * {@inheritDoc}//from www  .java  2  s  .co  m
 *
 * @throws IOException If the model file cannot be created or if there are problems accessing the input stream.
 * @throws ClassNotFoundException If there are problems interpreting the serialized data.
 * @throws ClassCastException If there are problems interpreting the serialized data.
 */
@Override
public CRFClassifier<CoreLabel> getNERModel() throws IOException, ClassNotFoundException {
    File file;
    file = getModelFile();
    final CRFClassifier<CoreLabel> crf = CRFClassifier.getClassifier(file);
    Files.delete(file.toPath());
    return crf;
}

From source file:com.seleniumtests.util.logging.SeleniumRobotLogger.java

public static void reset() throws IOException {
    SeleniumRobotLogger.testLogs.clear();

    // clear log file
    Appender fileAppender = Logger.getRootLogger().getAppender(FILE_APPENDER_NAME);
    if (fileAppender != null) {
        fileAppender.close();//from w  ww  . j  av  a2  s.c om

        // wait for handler to be closed
        WaitHelper.waitForMilliSeconds(200);
        Logger.getRootLogger().removeAppender(FILE_APPENDER_NAME);
    }
    Path logFilePath = Paths.get(outputDirectory, SeleniumRobotLogger.LOG_FILE_NAME).toAbsolutePath();
    if (logFilePath.toFile().exists()) {
        Files.delete(logFilePath);
    }
}