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.wso2.carbon.apimgt.core.impl.FileEncryptionUtility.java

/**
 * Creates and stores an AES key/*from www . ja va2  s  .com*/
 *
 * @throws APIManagementException if an error occurs while creating or storing AES key
 */
void createAndStoreAESKey() throws APIManagementException {
    try {
        //create a new AES key
        KeyGenerator keyGenerator = KeyGenerator.getInstance(EncryptionConstants.AES);
        keyGenerator.init(AES_Key_Size);
        byte[] aesKey = keyGenerator.generateKey().getEncoded();

        //store key => encrypt -> encode -> chars -> string
        byte[] encryptedKeyBytes = SecureVaultUtils.base64Encode(getSecureVault().encrypt(aesKey));
        String encryptedKeyString = new String(SecureVaultUtils.toChars(encryptedKeyBytes));

        Files.deleteIfExists(Paths.get(getAesKeyFileLocation()));
        APIFileUtils.createFile(getAesKeyFileLocation());
        APIFileUtils.writeToFile(getAesKeyFileLocation(), encryptedKeyString);
        log.debug("AES key successfully created and stored");
    } catch (NoSuchAlgorithmException | SecureVaultException | APIMgtDAOException | IOException e) {
        String msg = "Error while creating or storing created AES key";
        throw new APIManagementException(msg, e);
    }
}

From source file:org.wrml.runtime.service.file.FileSystemService.java

public static void writeModelFile(final Model model, final Path modelFilePath, final URI fileFormatUri,
        final ModelWriteOptions writeOptions) throws IOException, ModelWriterException {

    final Context context = model.getContext();
    OutputStream out = null;/*  w w w  .j  a  v  a2s. c  o m*/
    try {
        Files.createDirectories(modelFilePath.getParent());
        Files.deleteIfExists(modelFilePath);
        Files.createFile(modelFilePath);
        out = Files.newOutputStream(modelFilePath, StandardOpenOption.CREATE, StandardOpenOption.WRITE,
                StandardOpenOption.TRUNCATE_EXISTING);
    } catch (final IOException e) {
        IOUtils.closeQuietly(out);
        throw e;
    }

    try {
        context.writeModel(out, model, writeOptions, fileFormatUri);
    } catch (final ModelWriterException e) {
        IOUtils.closeQuietly(out);
        throw e;
    }

    IOUtils.closeQuietly(out);
}

From source file:edu.ehu.galan.lite.algorithms.unranked.supervised.shallowParsingGrammar.cg3.ShallowParsingGrammarAlgortithm.java

private void stringToTextFile(String sTream) {
    PrintWriter pw = null;/*  w w  w .j  ava  2s  . com*/
    try {
        Files.deleteIfExists(Paths.get(props.getProperty("tmpDir") + "cg3/text.txt"));
    } catch (IOException ex) {
        logger.warn("Error deleting temporal file for CG3 analysis", ex);
    }

    try (FileWriter fichero = new FileWriter(props.getProperty("tmpDir") + "cg3/text.txt")) {
        pw = new PrintWriter(fichero);
        pw.println(sTream);
    } catch (IOException e) {
        logger.error("Error while creating temporal text file for analysis", e);
    } finally {
        if (null != pw) {
            pw.close();
        }
    }

}

From source file:spade.utility.BitcoinTools.java

public Block getBlock(int blockIndex) throws JSONException {
    String file_path = new Formatter().format(BLOCK_JSON_FILE_FORMAT, blockIndex).toString();
    File f = new File(file_path);
    if (!f.exists()) {
        dumpBlock(blockIndex);/*from ww w  . j  a v  a 2  s.c  o  m*/
    }

    String line;
    StringBuffer jsonString = new StringBuffer();
    BufferedReader br;
    try {
        br = new BufferedReader(new InputStreamReader(new FileInputStream(file_path)));
        while ((line = br.readLine()) != null) {
            jsonString.append(line);
        }
        br.close();
    } catch (IOException e) {
        Bitcoin.log(Level.SEVERE, "Can't open and read file.", e);
    }

    if (BLOCK_JSON_DUMP_ENABLED == false) {
        try {
            Files.deleteIfExists(Paths.get(file_path));
        } catch (IOException ex) {
            Bitcoin.log(Level.SEVERE, "IO issue.", ex);
        }
    }

    return new Block(new JSONObject(jsonString.toString()));
}

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

@Test
public void createsContainerWithSignatureProfileTSForDDocReturnsFailureCode() throws Exception {
    exit.expectSystemExitWithStatus(1);// w ww.j  a v a2 s .c om

    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", "LT" };

    DigiDoc4J.main(params);
}

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

@Test
public final void testFetchAll() throws IOException {
    Set<File> files = new HashSet<>();
    for (int no = 0; no < 10; no++) {
        final File newFile = Files.createTempFile(tempFilePath, "xyz" + no, "txt").toFile();
        FileUtils.write(newFile, "Test", UTF_8);
        files.add(newFile);//from   ww  w . j av  a2  s. c  o  m
    }
    final Set<FileStoreMapper> maps = new HashSet<>();
    for (File file : files)
        maps.add(diskFileService.store(file, "fileName", "text/plain", "testmodule"));

    final Set<File> returnfiles = diskFileService.fetchAll(maps, "testmodule");
    assertNotNull(returnfiles);
    assertTrue(returnfiles.size() == 10);

    for (File file : files) {
        Files.deleteIfExists(file.toPath());
    }
}

From source file:io.specto.hoverfly.junit.core.Hoverfly.java

/**
 * Exports a simulation and stores it on the filesystem at the given path
 *
 * @param path the path on the filesystem to where the simulation should be stored
 *///w  w w .j a  va2s  . c  o m
public void exportSimulation(Path path) {

    if (path == null) {
        throw new IllegalArgumentException("Export path cannot be null.");
    }

    LOGGER.info("Exporting simulation data from Hoverfly");
    try {
        Files.deleteIfExists(path);
        final Simulation simulation = hoverflyClient.getSimulation();
        persistSimulation(path, simulation);
    } catch (Exception e) {
        LOGGER.error("Failed to export simulation data", e);
    }
}

From source file:com.qwazr.extractor.ExtractorServiceImpl.java

private ParserResult putMagicStream(final UriInfo uriInfo, final String fileName, String mimeType,
        final InputStream inputStream) throws Exception {

    Path tempFile = null;//  ww w . ja  v a2s.c o m
    try {
        Class<? extends ParserInterface> parserClass = null;

        // Find a parser with the extension
        String extension = null;
        if (!StringUtils.isEmpty(fileName)) {
            extension = FilenameUtils.getExtension(fileName);
            parserClass = getClassParserExtension(extension);
        }

        // Find a parser from the mime type
        if (parserClass == null) {
            if (StringUtils.isEmpty(mimeType)) {
                tempFile = Files.createTempFile("textextractor",
                        extension == null ? StringUtils.EMPTY : "." + extension);
                try {
                    IOUtils.copy(inputStream, tempFile);
                } finally {
                    IOUtils.closeQuietly((AutoCloseable) inputStream);
                }
                mimeType = getMimeMagic(tempFile);
            }
            if (!StringUtils.isEmpty(mimeType))
                parserClass = getClassParserMimeType(mimeType);
        }

        // Do the extraction
        final MultivaluedMap<String, String> queryParameters = getQueryParameters(uriInfo);
        final ParserInterface parser = getParser(parserClass);
        final ParserResultBuilder result = new ParserResultBuilder(parser);
        if (tempFile != null)
            parser.parseContent(queryParameters, tempFile, extension, mimeType, result);
        else
            parser.parseContent(queryParameters, inputStream, extension, mimeType, result);
        return result.build();
    } finally {
        if (tempFile != null)
            Files.deleteIfExists(tempFile);
    }
}