List of usage examples for java.nio.file Files deleteIfExists
public static boolean deleteIfExists(Path path) throws IOException
From source file:org.eclipse.packagedrone.utils.rpm.build.PayloadRecorder.java
public Result addFile(final String targetPath, final InputStream stream, final Consumer<CpioArchiveEntry> customizer) throws IOException { final Path tmpFile = Files.createTempFile("rpm-payload-", null); try {//from w ww .j av a 2 s. c o m try (OutputStream os = Files.newOutputStream(tmpFile)) { ByteStreams.copy(stream, os); } return addFile(targetPath, tmpFile, customizer); } finally { Files.deleteIfExists(tmpFile); } }
From source file:neembuu.uploader.zip.generator.NUZipFileGenerator.java
private void handleSmallModule(SmallModule moduleDescription, Class clzz, Path uploadersDirectory) throws IOException { Logger.getLogger(NUZipFileGenerator.class.getName()).log(Level.INFO, "Create zip for: {0}", clzz.getName()); Path outputModulePath = outputDirectory.resolve("sm").resolve(moduleDescription.name() + ".zip"); Files.createDirectories(outputModulePath.getParent()); while (Files.exists(outputModulePath)) { try {//w w w.j a va 2s . co m Files.deleteIfExists(outputModulePath); } catch (Exception a) { a.printStackTrace(); } } Map<String, String> env = new HashMap<>(); env.put("create", "true"); boolean destroyZipIsCorrupt = false; URI uri = URI.create("jar:" + outputModulePath.toUri()); try (FileSystem fs = FileSystems.newFileSystem(uri, env)) { smallModuleCreateZip(fs, moduleDescription, clzz, uploadersDirectory); } catch (Exception e) { e.printStackTrace(); destroyZipIsCorrupt = true; } if (destroyZipIsCorrupt) { Files.delete(outputModulePath); } else { String hash = HashUtil.hashFile(outputModulePath.toFile(), index.getHashalgorithm()); try { index.addSmallModule(moduleDescription, hash); } catch (Exception a) { a.printStackTrace();//ignore } } }
From source file:org.apache.asterix.external.feed.test.InputHandlerTest.java
private void cleanDiskFiles() throws IOException { String filePrefix = "dataverse.feed(Feed)_dataset*"; Collection<File> files = FileUtils.listFiles(new File("."), new WildcardFileFilter(filePrefix), null); for (File ifile : files) { Files.deleteIfExists(ifile.toPath()); }//from w ww . j a va2 s . c o m }
From source file:org.ballerinalang.test.packaging.PackagingNegativeTestCase.java
@Test(description = "Test pushing a package to central without Module.md") public void testPushWithoutModuleMD() throws Exception { Path projectPath = tempProjectDirectory.resolve("projectWithoutModuleMD"); initProject(projectPath);//from www . ja v a 2 s . c o m // Delete Module.md Path moduleMDFilePath = projectPath.resolve(moduleName).resolve("Module.md"); Files.deleteIfExists(moduleMDFilePath); String[] clientArgs = { moduleName }; String msg = "ballerina: cannot find Module.md file in the artifact"; balClient.runMain("push", clientArgs, envVariables, new String[0], new LogLeecher[] { new LogLeecher(msg) }, projectPath.toString()); }
From source file:com.codealot.textstore.FileStore.java
@Override public String storeText(final Reader reader) throws IOException { Objects.requireNonNull(reader, "No reader provided"); // make the digester final MessageDigest digester = getDigester(); // make temp file final Path textPath = Paths.get(this.storeRoot, UUID.randomUUID().toString()); // stream to file, building digest final ReaderInputStream readerAsBytes = new ReaderInputStream(reader, StandardCharsets.UTF_8); try {/*from w w w. j av a 2s.co m*/ final byte[] bytes = new byte[1024]; int readLength = 0; long totalRead = 0L; while ((readLength = readerAsBytes.read(bytes)) > 0) { totalRead += readLength; digester.update(bytes, 0, readLength); final byte[] readBytes = Arrays.copyOf(bytes, readLength); Files.write(textPath, readBytes, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND); } // check that something was read if (totalRead == 0L) { return this.storeText(""); } // make the hash final String hash = byteToHex(digester.digest()); // store the text, if new final Path finalPath = Paths.get(this.storeRoot, hash); if (Files.exists(finalPath)) { // already existed, so delete uuid named one Files.deleteIfExists(textPath); } else { // rename the file Files.move(textPath, finalPath); } return hash; } finally { if (readerAsBytes != null) { readerAsBytes.close(); } } }
From source file:org.digidoc4j.main.DigiDoc4JTest.java
@Test(expected = IllegalArgumentException.class) public void createsECCSignatureWithInvalidEncryptionType() throws Exception { String fileName = "createsECCSignatureWithInvalidEncryptionType.bdoc"; Files.deleteIfExists(Paths.get(fileName)); String[] params = new String[] { "-in", fileName, "-add", "testFiles/test.txt", "text/plain", "-pkcs12", "testFiles/ec-digiid.p12", "inno", "-e", "INVALID" }; DigiDoc4J.main(params);/*from ww w.j av a 2s . c o m*/ }
From source file:org.fcrepo.integration.connector.file.AbstractFedoraFileSystemConnectorIT.java
protected static void cleanUpJsonFilesFiles(final File directory) { final WildcardFileFilter filter = new WildcardFileFilter("*.modeshape.json"); final Collection<File> files = FileUtils.listFiles(directory, filter, TrueFileFilter.INSTANCE); final Iterator<File> iterator = files.iterator(); // Clean up files persisted in previous runs while (iterator.hasNext()) { final File f = iterator.next(); final String path = f.getAbsolutePath(); try {/* www. j a v a 2s. c o m*/ Files.deleteIfExists(Paths.get(path)); } catch (final IOException e) { logger.error("Error in clean up", e); fail("Unable to delete work files from a previous test run. File=" + path); } } }
From source file:com.vns.pdf.impl.PdfDocument.java
void close() throws IOException { try { document.close(); } catch (Exception ex) { } Files.deleteIfExists(pdfTempDir); }
From source file:com.hpe.caf.worker.testing.validation.ReferenceDataValidator.java
@Override public boolean isValid(Object testedPropertyValue, Object validatorPropertyValue) { if (testedPropertyValue == null && validatorPropertyValue == null) return true; ObjectMapper mapper = new ObjectMapper(); ContentFileTestExpectation expectation = mapper.convertValue(validatorPropertyValue, ContentFileTestExpectation.class); ReferencedData referencedData = mapper.convertValue(testedPropertyValue, ReferencedData.class); InputStream dataStream;/*from w ww.j a va 2 s. com*/ if (expectation.getExpectedContentFile() == null && expectation.getExpectedSimilarityPercentage() == 0) { return true; } try { System.out.println("About to retrieve content for " + referencedData.toString()); dataStream = ContentDataHelper.retrieveReferencedData(dataStore, codec, referencedData); System.out.println("Finished retrieving content for " + referencedData.toString()); } catch (DataSourceException e) { e.printStackTrace(); System.err.println("Failed to acquire referenced data."); e.printStackTrace(); TestResultHelper.testFailed("Failed to acquire referenced data. Exception message: " + e.getMessage(), e); return false; } try { String contentFileName = expectation.getExpectedContentFile(); Path contentFile = Paths.get(contentFileName); if (Files.notExists(contentFile) && !Strings.isNullOrEmpty(testSourcefileBaseFolder)) { contentFile = Paths.get(testSourcefileBaseFolder, contentFileName); } if (Files.notExists(contentFile)) { contentFile = Paths.get(testDataFolder, contentFileName); } byte[] expectedFileBytes = Files.readAllBytes(contentFile); if (expectation.getComparisonType() == ContentComparisonType.TEXT) { String actualText = IOUtils.toString(dataStream, StandardCharsets.UTF_8); String expectedText = new String(expectedFileBytes, StandardCharsets.UTF_8); if (expectation.getExpectedSimilarityPercentage() == 100) { boolean equals = actualText.equals(expectedText); if (!equals) { String message = "Expected and actual texts were different.\n\n*** Expected Text ***\n" + expectedText + "\n\n*** Actual Text ***\n" + actualText; System.err.println(message); if (throwOnValidationFailure) TestResultHelper.testFailed(message); return false; } return true; } double similarity = ContentComparer.calculateSimilarityPercentage(expectedText, actualText); System.out.println("Compared text similarity:" + similarity + "%"); if (similarity < expectation.getExpectedSimilarityPercentage()) { String message = "Expected similarity of " + expectation.getExpectedSimilarityPercentage() + "% but actual similarity was " + similarity + "%"; System.err.println(message); if (throwOnValidationFailure) TestResultHelper.testFailed(message); return false; } } else { byte[] actualDataBytes = IOUtils.toByteArray(dataStream); boolean equals = Arrays.equals(actualDataBytes, expectedFileBytes); if (!equals) { String actualContentFileName = contentFile.getFileName() + "_actual"; Path actualFilePath = Paths.get(contentFile.getParent().toString(), actualContentFileName); Files.deleteIfExists(actualFilePath); Files.write(actualFilePath, actualDataBytes, StandardOpenOption.CREATE); String message = "Data returned was different than expected for file: " + contentFileName + "\nActual content saved in file: " + actualFilePath.toString(); System.err.println(message); if (throwOnValidationFailure) TestResultHelper.testFailed(message); return false; } } } catch (IOException e) { e.printStackTrace(); TestResultHelper.testFailed("Error while processing reference data! " + e.getMessage(), e); return false; } return true; }
From source file:org.eclipse.vorto.remoterepository.internal.dao.FilesystemModelDAO.java
@Override public ModelView saveModel(ModelContent modelContent) { ModelId mID = modelContent.getModelId(); ModelView mv = ModelFactory.newModelView(mID, "Newly Added Model, ...."); Path dirToSave = this.resolveDirectoryPathToModel(mID); Path fileToSave = this.resolvePathToModel(mID); try {// ww w .j a va2s.c om if (!Files.exists(dirToSave)) { Files.createDirectories(dirToSave); } if (!Files.exists(fileToSave)) { Files.createFile(fileToSave); } else { Files.deleteIfExists(fileToSave); } Files.write(fileToSave, modelContent.getContent(), StandardOpenOption.TRUNCATE_EXISTING); return mv; } catch (IOException e) { throw new RuntimeException("An I/O error was thrown while saving new model file: " + mID.toString(), e); } }