Example usage for java.nio.file Files deleteIfExists

List of usage examples for java.nio.file Files deleteIfExists

Introduction

In this page you can find the example usage for java.nio.file Files deleteIfExists.

Prototype

public static boolean deleteIfExists(Path path) throws IOException 

Source Link

Document

Deletes a file if it exists.

Usage

From source file:com.altoukhov.svsync.fileviews.LocalFileSpace.java

@Override
public boolean deleteFile(String path) {
    try {/*from w w  w  .j a v a  2 s  .  c  o  m*/
        return Files.deleteIfExists(Paths.get(toAbsolutePath(path)));
    } catch (IOException ex) {
        System.out.println("Failed to delete file: " + ex.getMessage());
    }

    return false;
}

From source file:org.wte4j.ui.server.services.TemplateRestServiceTest.java

@Test
public void uploadTempFile() throws Exception {
    ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.fileUpload("/templates/temp")
            .file("file", "test".getBytes()).param("name", "fileName"));

    String content = resultActions.andReturn().getResponse().getContentAsString();

    resultActions.andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentType("text/html;charset=UTF-8"));

    ObjectMapper mapper = new ObjectMapper();
    FileUploadResponseDto dto = mapper.readValue(content, FileUploadResponseDto.class);

    Path file = Paths.get(dto.getMessage());
    try {//from ww  w  .  j a  v a  2 s .c  o m
        assertTrue("file " + file + "must exist", Files.exists(file));

    } finally {
        Files.deleteIfExists(file);
    }

}

From source file:org.apache.marmotta.loader.statistics.Statistics.java

public void stopSampling() {
    if (statSampler != null) {
        statSampler.shutdown();//w ww.  ja va  2  s . c  om
    }

    if (diagramUpdater != null) {
        diagramUpdater.run();
    }

    if (statDB != null) {
        try {
            statDB.close();
        } catch (IOException e) {
            log.warn("could not close statistics database...");
        }
    }

    try {
        Files.deleteIfExists(statFile);
    } catch (IOException e) {
        log.warn("could not cleanup statistics database: {}", e.getMessage());
    }
}

From source file:at.tfr.securefs.ws.FileServiceBean.java

/**
 * Delete file if it exists./*from   ww w . jav  a 2s.c  o m*/
 * @param relPath
 * @return
 * @throws IOException
 * @see Files#deleteIfExists(java.nio.file.Path) 
 */
@WebMethod
@Override
public boolean delete(String relPath) throws IOException {
    try {
        Path path = SecureFileSystemBean.resolvePath(relPath, configuration.getBasePath(),
                configuration.isRestrictedToBasePath());
        if (!Files.isRegularFile(path) || !Files.isReadable(path)) {
            throw new IOException("invalid path: " + relPath);
        }
        log.debug("delete File: " + relPath + " as " + path);
        boolean deleted = Files.deleteIfExists(path);
        logInfo("deleted File: " + path + " : " + deleted, null);
        return deleted;
    } catch (Exception e) {
        logInfo("read File failed: " + relPath, e);
        log.warn("read File failed: " + relPath + e);
        throw e;
    }
}

From source file:org.digidoc4j.DataFileTest.java

@Test
public void createDocumentFromStream() throws Exception {
    try (ByteArrayInputStream inputStream = new ByteArrayInputStream("tere tere tipajalga".getBytes())) {
        DataFile dataFile = new DataFile(inputStream, "test.txt", "text/plain");
        dataFile.saveAs("createDocumentFromStream.txt");

        DataFile dataFileToCompare = new DataFile("createDocumentFromStream.txt", "text/plain");
        assertArrayEquals("tere tere tipajalga".getBytes(), dataFileToCompare.getBytes());
    }/*from   w w  w  . ja va  2s.co  m*/

    Files.deleteIfExists(Paths.get("createDocumentFromStream.txt"));
}

From source file:org.eclipse.che.api.fs.server.impl.FsOperations.java

void deleteIfExists(Path fsPath) throws ServerException {
    if (!Files.exists(fsPath)) {
        return;//  www  . j ava  2  s  . c  o  m
    }

    try {
        if (Files.isDirectory(fsPath)) {
            FileUtils.deleteDirectory(fsPath.toFile());
        } else {
            Files.deleteIfExists(fsPath);
        }
    } catch (IOException e) {
        throw new ServerException("Failed to delete item: " + fsPath, e);
    }
}

From source file:com.arpnetworking.metrics.impl.StenoLogSinkTest.java

@Test
public void testSerialization() throws IOException, InterruptedException {
    final File actualFile = new File("./target/StenoLogSinkTest/testSerialization-Query.log");
    Files.deleteIfExists(actualFile.toPath());
    final Sink sink = new StenoLogSink.Builder().setDirectory(createDirectory("./target/StenoLogSinkTest"))
            .setName("testSerialization-Query").setImmediateFlush(Boolean.TRUE).build();

    final Map<String, String> annotations = new LinkedHashMap<>(ANNOTATIONS);
    annotations.put("foo", "bar");
    sink.record(new TsdEvent(annotations, TEST_SERIALIZATION_TIMERS, TEST_SERIALIZATION_COUNTERS,
            TEST_SERIALIZATION_GAUGES));

    // TODO(vkoskela): Add protected option to disable async [MAI-181].
    Thread.sleep(100);//  w ww . j av  a2  s . c o m

    final String actualOriginalJson = fileToString(actualFile);
    assertMatchesJsonSchema(actualOriginalJson);
    final String actualComparableJson = actualOriginalJson
            .replaceAll("\"time\":\"[^\"]*\"", "\"time\":\"<TIME>\"")
            .replaceAll("\"threadId\":\"[^\"]*\"", "\"threadId\":\"<THREADID>\"")
            .replaceAll("\"processId\":\"[^\"]*\"", "\"processId\":\"<PROCESSID>\"")
            .replaceAll("\"host\":\"[^\"]*\"", "\"host\":\"<HOST>\"")
            .replaceAll("\"id\":\"[^\"]*\"", "\"id\":\"<ID>\"");
    final JsonNode actual = OBJECT_MAPPER.readTree(actualComparableJson);
    final JsonNode expected = OBJECT_MAPPER.readTree(EXPECTED_METRICS_JSON);

    Assert.assertEquals("expectedJson=" + OBJECT_MAPPER.writeValueAsString(expected) + " vs actualJson="
            + OBJECT_MAPPER.writeValueAsString(actual), expected, actual);
}

From source file:hydrograph.ui.graph.debug.service.PurgeViewDataFiles.java

/**
 * Purge the file on specific path/*from ww w.  j  a v a  2 s . c o m*/
 * @param filePath
 */
private void removeFiles(String filePath) {
    try {
        File file = new File(filePath);
        boolean result = Files.deleteIfExists(file.toPath());
        if (result) {
            logger.debug(filePath + " file deleted.");
        }
    } catch (Exception exception) {
        logger.error("Failed to remove ViewExecutionHistory log file.", exception);
    }
}

From source file:misc.FileHandler.java

/**
 * Copies the source file with the given options to the target file. The
 * source is first copied to the system's default temporary directory and
 * the temporary copy is then moved to the target file. In order to avoid
 * performance problems, the file is directly copied from the source to a
 * temporary file in the target directory first, if the temporary directory
 * and the target file lie on a different <code>FileStore</code>. The
 * temporary file is also moved to the target file.
 * /*  ww  w  . jav a2 s.com*/
 * @param source
 *            the file to copy.
 * @param target
 *            the target location where the file should be stored. Must not
 *            be identical with source. The file might or might not exist.
 *            The parent directory must exist.
 * @param replaceExisting
 *            <code>true</code>, if the target file may be overwritten.
 *            Otherwise, <code>false</code>.
 * @return <code>true</code>, if the file was successfully copied.
 *         Otherwise, <code>false</code>.
 */
public static boolean copyFile(Path source, Path target, boolean replaceExisting) {
    if ((source == null) || !Files.isReadable(source)) {
        throw new IllegalArgumentException("source must exist and be readable!");
    }
    if (target == null) {
        throw new IllegalArgumentException("target may not be null!");
    }
    if (source.toAbsolutePath().normalize().equals(target.toAbsolutePath().normalize())) {
        throw new IllegalArgumentException("source and target must not match!");
    }

    boolean success = false;
    Path tempFile = null;

    target = target.normalize();

    try {
        tempFile = FileHandler.getTempFile(target);

        if (tempFile != null) {
            Files.copy(source, tempFile, StandardCopyOption.COPY_ATTRIBUTES,
                    StandardCopyOption.REPLACE_EXISTING);
            if (replaceExisting) {
                Files.move(tempFile, target, StandardCopyOption.REPLACE_EXISTING);
            } else {
                Files.move(tempFile, target);
            }
            success = true;
        }
    } catch (IOException e) {
        Logger.logError(e);
    } finally {
        if (tempFile != null) {
            try {
                Files.deleteIfExists(tempFile);
            } catch (IOException eDelete) {
                Logger.logError(eDelete);
            }
        }
    }

    return success;
}

From source file:org.apache.marmotta.platform.ldp.services.LdpBinaryStoreServiceImpl.java

@Override
public boolean delete(String resource) {
    try {/*from www  .  j a  v a2  s . c  om*/
        final Path file = getFile(resource);
        return Files.deleteIfExists(file);
    } catch (IOException | URISyntaxException e) {
        log.error("Error while deleting {}: {}", resource, e.getMessage());
        return false;
    }
}