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.eclipse.packagedrone.utils.rpm.build.PayloadRecorder.java

@Override
public void close() throws IOException {
    this.closed = true;

    try {//w w w  . ja v a2s.  c o  m
        // simply close the file stream

        if (this.fileStream != null) {
            this.fileStream.close();
        }
    } finally {
        // and delete the temp file

        Files.deleteIfExists(this.tempFile);
    }
}

From source file:org.egov.infra.filestore.service.impl.LocalDiskFileStoreServiceTest.java

@Test
public final void testDeleteFile() throws IOException {
    final File newFile = Files.createTempFile(tempFilePath, "xyz", "txt").toFile();
    FileUtils.write(newFile, "Test", UTF_8);
    FileStoreMapper fileStoreMapper = diskFileService.store(newFile, "fileName", "text/plain", "testmodule");
    diskFileService.delete(fileStoreMapper.getFileStoreId(), "testmodule");
    Files.deleteIfExists(newFile.toPath());
}

From source file:org.digidoc4j.main.DigiDoc4JTest.java

@Test
public void createsContainerWithSignatureProfileTSAForDDocReturnsFailureCode() throws Exception {
    exit.expectSystemExitWithStatus(1);//from   ww  w .  j  a  v a 2  s  .c  o  m

    String fileName = "test1.ddoc";
    Files.deleteIfExists(Paths.get(fileName));

    String[] params = new String[] { "-in", fileName, "-type", "DDOC", "-add", "testFiles/test.txt",
            "text/plain", "-pkcs12", "testFiles/signout.p12", "test", "-profile", "LTA" };

    DigiDoc4J.main(params);
}

From source file:org.whitesource.agent.utils.ZipUtils.java

/**
 * The method compresses the big strings using gzip - low memory via the File system
 *
 * @param text The string to compress.// ww  w  . j ava2 s  .c o  m
 * @return The compressed string.
 * @throws java.io.IOException
 */
public static String compressChunks(String text) throws IOException {
    Path tempFolder = Paths.get(JAVA_TEMP_DIR, ZIP_UTILS);
    File tempFileIn = File.createTempFile(TMP_IN_, ZIP_UTILS_SUFFIX, tempFolder.toFile());
    File tempFileOut = File.createTempFile(TMP_OUT_, ZIP_UTILS_SUFFIX, tempFolder.toFile());

    writeChunkBytes(text, tempFileIn);
    String result;
    if (text != null && text.length() > 0) {
        try (InputStream in = new FileInputStream(tempFileIn);
                FileOutputStream fileOutputStream = new FileOutputStream(tempFileOut);
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
                OutputStream out = new GZIPOutputStream(bufferedOutputStream);) {

            byte[] bytes = new byte[BYTES_BUFFER_SIZE];
            int len;
            while ((len = in.read(bytes)) > 0) {
                out.write(bytes, 0, len);
            }

            in.close();
            out.flush();
            out.close();

            // result = new BASE64Encoder().encode(Files.readAllBytes(tempFileOut.toPath()));
            result = Base64.encodeBase64String(Files.readAllBytes(tempFileOut.toPath()));
        }
    } else {
        result = text;
    }

    Files.deleteIfExists(tempFileIn.toPath());
    Files.deleteIfExists(tempFileOut.toPath());

    return result;
}

From source file:org.ballerinalang.ballerina.openapi.convertor.service.OpenApiConverterUtils.java

/**
 * Write content to a file./*from   www .  ja v a 2 s.c o m*/
 *
 * @param path    Path of the file.
 * @param content The content.
 * @throws IOException Error when creating or writing the file.
 */
private static void writeFile(Path path, String content) throws IOException {
    Path parentPath = path.getParent();
    if (null != parentPath && Files.exists(parentPath)) {
        Files.createDirectories(parentPath);
    }
    Files.deleteIfExists(path);
    Files.createFile(path);
    try (PrintWriter writer = new PrintWriter(path.toString(), "UTF-8")) {
        writer.print(content);
    }
}

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

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

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

    // TODO(vkoskela): Add protected option to disable async [MAI-181].
    Thread.sleep(100);/*  ww  w .ja  v a 2 s  .c om*/

    final String actualOriginalJson = fileToString(actualFile);
    assertMatchesJsonSchema(actualOriginalJson);
    final String actualComparableJson = actualOriginalJson
            .replaceAll("\"time\":\"[^\"]*\"", "\"time\":\"<TIME>\"")
            .replaceAll("\"host\":\"[^\"]*\"", "\"host\":\"<HOST>\"")
            .replaceAll("\"processId\":\"[^\"]*\"", "\"processId\":\"<PROCESSID>\"")
            .replaceAll("\"threadId\":\"[^\"]*\"", "\"threadId\":\"<THREADID>\"")
            .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:org.elasticwarehouse.core.graphite.RRDManager.java

public static boolean expandRRDFile(String tmpfolder, String filenamepath, LinkedList<String> customattributes,
        String targetfilenamepath) throws IOException, ParseException {
    //sources_ = customattributes;
    //RrdDef def = rrdDb_.getRrdDef();
    LinkedList<DsDef> newdefs = new LinkedList<DsDef>();
    //String[] datasources = rrdDb_.getDsNames();
    //initDataSources(customattributes, true);
    for (String sourceName : customattributes/*sources_*/) {
        /*boolean found = false;
        for(String currentsourceName : datasources)
          {//from  w w  w .  j  a v a2 s . com
           if( currentsourceName.equals(sourceName) )
           {
              found = true;
              break;
           }
          }*/
        //if( !found )
        //{
        LOGGER.info("Adding: " + sourceName + " in " + targetfilenamepath + "(org:" + filenamepath + ")");
        //def.addDatasource(sourceName, GAUGE, 600, 0, Double.NaN);
        newdefs.add(new DsDef(sourceName, GAUGE, 600, 0, Double.NaN));
        //}
    }
    if (!newdefs.isEmpty()) {
        /*if( rrdDb_ != null )
        {
           rrdDb_.close();
           rrdDb_ = null;
        }*/

        MonitoringManager.closeFilesInElasticSearchMonitors();

        String tmpFilename = tmpfolder + "/" + FilenameUtils.getBaseName(filenamepath) + ".rrd.tmp";
        //String tmpFilenameCopy = tmpfolder+"/"+FilenameUtils.getBaseName(filenamepath)+".rrd.tmpcopy";

        Files.deleteIfExists(new File(tmpFilename).toPath());
        //Files.deleteIfExists(new File(tmpFilenameCopy).toPath());
        FileTools.copy(filenamepath, tmpFilename);
        /*int attemp=0;
        for(;;)
        {
           if( attemp == 5)
              break;
           try{
              attemp++;
              Files.deleteIfExists(new File(filenamepath).toPath());
              break;
           }catch(java.nio.file.FileSystemException e)
           {
              LOGGER.info("Got java.nio.file.FileSystemException, waiting...." + e.getMessage() );
           }
           try
           {
              Thread.sleep(2300);
           }catch(InterruptedException e)
           {
              EWLogger.logerror(e);
           }
        }*/

        //if( attemp < 5) 
        //{
        RrdToolkit.addDatasources(tmpFilename, targetfilenamepath, newdefs);
        //FileTools.copy(tmpFilename, filenamepath);
        MonitoringManager.reopenFilesInElasticSearchMonitors();
        Files.deleteIfExists(new File(tmpFilename).toPath());
        //Files.deleteIfExists(new File(tmpFilenameCopy).toPath());
        //}
    }
    return true;
}

From source file:org.digidoc4j.main.DigiDoc4JTest.java

@Test
@Ignore("JDigiDoc by default returns LT_TM profile but should be B_BES profile")
public void createsContainerWithSignatureProfileBESForDDoc() throws Exception {
    String fileName = "test1.ddoc";
    Files.deleteIfExists(Paths.get(fileName));

    String[] params = new String[] { "-in", fileName, "-type", "DDOC", "-add", "testFiles/test.txt",
            "text/plain", "-pkcs12", "testFiles/signout.p12", "test", "-profile", "B_BES" };

    callMainWithoutSystemExit(params);//from  ww w .j  a  v  a2 s  .  c  o m

    Container container = ContainerOpener.open(fileName);
    assertEquals(SignatureProfile.B_BES, container.getSignature(0).getProfile());
}

From source file:de.digiway.rapidbreeze.server.model.download.Download.java

/**
 * Removes the temporary file where the download is streamed to. The
 * download must be waiting or error.//from   w ww  .  j  a  v a  2s  .  co  m
 */
public void removeTempFile() {
    if (!getDownloadStatus().equals(DownloadStatus.WAITING)
            && !getDownloadStatus().equals(DownloadStatus.ERROR)) {
        throw new IllegalStateException("Cannot remove temporary file. " + Download.class.getSimpleName()
                + " must be in state " + DownloadStatus.WAITING + " or " + DownloadStatus.ERROR);
    }

    try {
        Files.deleteIfExists(tempFile);
    } catch (IOException ex) {
        LOG.log(Level.WARNING, "Error removing temporary download file.", ex);
    }
}