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:org.apache.logging.log4j.core.appender.rolling.action.CommonsCompressAction.java

/**
 * Compresses a file.//from   w  ww . j  a  va  2  s.  com
 *
 * @param name the compressor name, i.e. "gz", "bzip2", "xz", "pack200", or "deflate".
 * @param source file to compress, may not be null.
 * @param destination compressed file, may not be null.
 * @param deleteSource if true, attempt to delete file on completion. Failure to delete does not cause an exception
 *            to be thrown or affect return value.
 *
 * @return true if source file compressed.
 * @throws IOException on IO exception.
 */
public static boolean execute(final String name, final File source, final File destination,
        final boolean deleteSource) throws IOException {
    if (!source.exists()) {
        return false;
    }
    LOGGER.debug("Starting {} compression of {}", name, source.getPath());
    try (final FileInputStream input = new FileInputStream(source);
            final BufferedOutputStream output = new BufferedOutputStream(new CompressorStreamFactory()
                    .createCompressorOutputStream(name, new FileOutputStream(destination)))) {
        IOUtils.copy(input, output, BUF_SIZE);
        LOGGER.debug("Finished {} compression of {}", name, source.getPath());
    } catch (final CompressorException e) {
        throw new IOException(e);
    }

    if (deleteSource) {
        try {
            if (Files.deleteIfExists(source.toPath())) {
                LOGGER.debug("Deleted {}", source.toString());
            } else {
                LOGGER.warn("Unable to delete {} after {} compression. File did not exist", source.toString(),
                        name);
            }
        } catch (Exception ex) {
            LOGGER.warn("Unable to delete {} after {} compression, {}", source.toString(), name,
                    ex.getMessage());
        }
    }

    return true;
}

From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java

@Test
public void testRegularFile() throws IOException {
    final Path tempDir = Files.createTempDirectory("ds3_file_object_putter_");
    final Path tempPath = Files.createTempFile(tempDir, "temp_", ".txt");

    try {//from   w  w  w  .j a v a  2  s.co  m
        try (final SeekableByteChannel channel = Files.newByteChannel(tempPath, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(testData));
        }

        getFileWithPutter(tempDir, tempPath);
    } finally {
        Files.deleteIfExists(tempPath);
        Files.deleteIfExists(tempDir);
    }
}

From source file:org.apache.archiva.checksum.ChecksummedFile.java

/**
 * Creates a checksum file of the provided referenceFile.
 *
 * @param checksumAlgorithm the hash to use.
 * @return the checksum File that was created.
 * @throws IOException if there was a problem either reading the referenceFile, or writing the checksum file.
 *//*from   w  w  w  .j  a v  a  2s  .c om*/
public File createChecksum(ChecksumAlgorithm checksumAlgorithm) throws IOException {
    File checksumFile = new File(referenceFile.getAbsolutePath() + "." + checksumAlgorithm.getExt());
    Files.deleteIfExists(checksumFile.toPath());
    String checksum = calculateChecksum(checksumAlgorithm);
    Files.write(checksumFile.toPath(), //
            (checksum + "  " + referenceFile.getName()).getBytes(), //
            StandardOpenOption.CREATE_NEW);
    return checksumFile;
}

From source file:com.pentaho.ctools.issues.cde.CDE417.java

/**
 * The function will delete the export file.
 */// w  w w . java  2  s.  co  m
public void DeleteFile() {
    try {
        Files.deleteIfExists(Paths.get(this.exportFilePath));
        Files.deleteIfExists(Paths.get(this.exportFilePath2));
    } catch (Exception e) {
        this.log.error(e.getMessage());
    }
}

From source file:org.eclipse.packagedrone.utils.rpm.build.PayloadRecorder.java

public PayloadRecorder(final boolean autoFinish) throws IOException {
    this.autoFinish = autoFinish;

    this.tempFile = Files.createTempFile("rpm-", null);

    try {//from w ww .  j  a  v  a 2 s  .com
        this.fileStream = new BufferedOutputStream(Files.newOutputStream(this.tempFile,
                StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING));

        this.payloadCounter = new CountingOutputStream(this.fileStream);

        final GZIPOutputStream payloadStream = new GZIPOutputStream(this.payloadCounter);
        this.archiveCounter = new CountingOutputStream(payloadStream);

        // setup archive stream

        this.archiveStream = new CpioArchiveOutputStream(this.archiveCounter, CpioConstants.FORMAT_NEW, 4,
                "UTF-8");
    } catch (final IOException e) {
        Files.deleteIfExists(this.tempFile);
        throw e;
    }
}

From source file:com.pentaho.ctools.issues.cda.CDAExportToXls.java

/**
 * The function will delete the export file.
 *//*w ww  . j av a 2 s.c o m*/
public void DeleteFile() {
    try {
        Files.deleteIfExists(Paths.get(this.exportFilePath));
    } catch (Exception e) {
        this.log.error(e.getMessage());
    }
}

From source file:edu.harvard.iq.dataverse.ThemeWidgetFragment.java

@PreDestroy
/**//  ww  w  .  j av  a 2 s. co  m
 *  Cleanup by deleting temp directory and uploaded files  
 */
public void cleanupTempDirectory() {
    try {

        if (tempDir != null) {
            for (File f : tempDir.listFiles()) {
                Files.deleteIfExists(f.toPath());
            }
            Files.deleteIfExists(tempDir.toPath());
        }
    } catch (IOException e) {
        throw new RuntimeException("Error deleting temp directory", e); // improve error handling
    }
    uploadedFile = null;
    tempDir = null;
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.tests.integration.HtmlToMobiConverterTest.java

@After
public void tearDown() throws Exception {
    if (mobi != null) {
        logger.debug("Removing generated mobi file");
        Files.deleteIfExists(mobi.toPath());
    }/*from   ww  w. jav  a 2  s . c o  m*/
}

From source file:uk.ac.kcl.texthunter.utils.Utils.java

public static boolean deleteFile(File file) throws InterruptedException, IOException {

    for (int i = 0; i <= 5; i++) {
        try {/*from w w  w.jav a2 s. c o  m*/
            if (file.exists()) {
                if (file.isDirectory()) {
                    FileUtils.deleteDirectory(file);
                    return true;
                } else {
                    Files.deleteIfExists(file.toPath());
                    return true;
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(Utils.class.getName()).log(Level.INFO, null,
                    "Deleting file " + file.getName() + " attempt " + i);
            Thread.sleep(500);
        }
    }
    if (file.exists()) {
        if (file.isDirectory()) {
            FileUtils.deleteDirectory(file);
            return true;
        } else {
            Files.deleteIfExists(file.toPath());
            return true;
        }
    }
    return false;
}