Java Code Examples for java.nio.file.Files.deleteIfExists()

The following are Jave code examples for showing how to use deleteIfExists() of the java.nio.file.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: jdk8u-jdk   File: BytesAndLines.java   Source Code and License Vote up 6 votes
/**
 * Exercise Files.readAllBytes(Path) on custom file system. This is special
 * because readAllBytes was originally implemented to use FileChannel
 * and so may not be supported by custom file system providers.
 */
public void testReadAllBytesOnCustomFS() throws IOException {
    Path myfile = PassThroughFileSystem.create().getPath("myfile");
    try {
        int size = 0;
        while (size <= 1024) {
            byte[] b1 = genBytes(size);
            Files.write(myfile, b1);
            byte[] b2 = Files.readAllBytes(myfile);
            assertTrue(Arrays.equals(b1, b2), "bytes not equal");
            size += 512;
        }
    } finally {
        Files.deleteIfExists(myfile);
    }
}
 
Example 2
Project: reactivejournal   File: ReactiveJournal.java   Source Code and License Vote up 6 votes
/**
 * Clear this ReactiveJournal's {@link #getDir() data directory} from ReactiveJournal-specific binary files, and remove it as
 * well (but only if it has become empty). If other files have been created inside the data directory, it is the
 * responsibility of the user to delete them AND the data directory.
 *
 * @throws IOException in case of directory traversal or file deletion problems
 */
public void clearCache() throws IOException {
    LOG.info("Deleting existing recording [{}]", dir);
    Path journalDir = Paths.get(dir);
    if(Files.exists(journalDir)) {
        Files.walk(journalDir)
                .map(Path::toFile)
                .filter(f -> f.isFile() && f.getName().endsWith(".cq4"))
                .peek(f -> LOG.info("Removing {}", f.getName()))
                .forEach(File::delete);

        try {
            Files.deleteIfExists(journalDir);
        } catch (DirectoryNotEmptyException e) {
            LOG.info("Directory does not only contain cq4 files, not deleted");
        }
    }
}
 
Example 3
Project: Dragonfly   File: PathUtil.java   Source Code and License Vote up 6 votes
public static void deleteTaskFiles(String taskId, boolean deleteUploadPath) {
    try {
        Path downPath = getDownloadPath(taskId);
        Files.deleteIfExists(downPath);

        if (deleteUploadPath) {
            Files.deleteIfExists(getUploadPath(taskId));
        }

        Files.deleteIfExists(getMetaDataPath(taskId));
        Files.deleteIfExists(getMd5DataPath(taskId));

    } catch (Exception e) {
        logger.error("delete files error for taskId:{}", taskId, e);
    }
}
 
Example 4
Project: oscm   File: LoggerInitListenerTest.java   Source Code and License Vote up 5 votes
private void emptyLogsFolder() throws IOException {
    logsFolder = new File("./javares/logs");
    if (!logsFolder.exists()) {
        logsFolder.mkdirs();
    } else {
        for (File file : logsFolder.listFiles()) {
            Files.deleteIfExists(file.toPath());
        }
    }
}
 
Example 5
Project: osc-core   File: ArchiveUtilTest.java   Source Code and License Vote up 5 votes
private void removeFilesAndEmptyDirs(List<String> dirsToRetry, Map.Entry<String, String> k) {
    try {
        Files.deleteIfExists(Paths.get(PATH + SEPARATOR + k.getKey()));
    } catch (IOException e) {
        if(e instanceof DirectoryNotEmptyException) {
            dirsToRetry.add(k.getKey());
        } else {
            e.printStackTrace();
        }
    }
}
 
Example 6
Project: openjdk-jdk10   File: DupImport.java   Source Code and License Vote up 5 votes
public static void main(String[] args) throws Exception {

        storeType = args[0];
        Files.deleteIfExists(Paths.get("dup.ks"));

        // Create chain: root -> int -> me
        run("-genkeypair -alias me -dname CN=Me");
        run("-genkeypair -alias int -dname CN=Int");
        run("-genkeypair -alias root -dname CN=Root");

        run("-certreq -alias int -file int.req");
        run("-gencert -infile int.req -alias root -rfc -outfile int.resp");
        run("-importcert -file int.resp -alias int");

        run("-certreq -alias me -file me.req");
        run("-gencert -infile me.req -alias int -rfc -outfile me.resp");
        run("-importcert -file me.resp -alias me");

        // Export certs
        run("-exportcert -alias me -file me -rfc");
        run("-exportcert -alias int -file int -rfc");
        run("-exportcert -alias root -file root -rfc");

        // test 1: just the 3 certs
        test("me", "int", "root");

        // test 2: 3 chains (without root) concatenated
        test("me", "int", "int", "root");

        // test 3: 3 full chains concatenated
        test("me", "int", "root", "int", "root", "root");

        // test 4: a mess
        test("root", "me", "int", "int", "me", "me", "root", "int");
    }
 
Example 7
Project: pgcodekeeper   File: PgDbParser.java   Source Code and License Vote up 5 votes
public static void clean(String name) {
    try {
        Path path = getPathToObject(name);
        Files.deleteIfExists(path);
    } catch (URISyntaxException | IOException e) {
        Log.log(Log.LOG_DEBUG, "Error while clean parser!", e); //$NON-NLS-1$
    }
}
 
Example 8
Project: sierra   File: FastaUtilsTest.java   Source Code and License Vote up 5 votes
@Test
public void testWriteFile() throws IOException {
	List<Sequence> sequences = new ArrayList<>();
	sequences.add(new Sequence(
		"seq1", "AV---GTACGTACGTACGTCATGCATGCATGCATGTAGCTAGCTAGCTAGC..."));
	sequences.add(new Sequence(
		"seq2-cc.z", "ACGTACGTACGAACGTCATGCATCCATGCATGTAGCTAGCTAGCTAGC"));
	sequences.add(new Sequence(
		"seq3", "RMRHARMSSDVN"));
	String testFilePath = "/tmp/fastaUtilsWriteFile.fasta";
	FastaUtils.writeFile(sequences, testFilePath);
	String result = new String(Files.readAllBytes(Paths.get(testFilePath)));
	String expecteds =
		">seq1\n" +
		"AVGTACGTACGTACGTCATGCATGCATGCATGTAGCTAGCTAGCTAGC\n" +
		">seq2-cc.z\n" +
		"ACGTACGTACGAACGTCATGCATCCATGCATGTAGCTAGCTAGCTAGC\n" +
		">seq3\n" +
		"RMRHARMSSDVN\n";
	assertEquals(expecteds, result);
	Files.deleteIfExists(Paths.get(testFilePath));

	FastaUtils.writeFile(sequences.get(0), testFilePath);
	result = new String(Files.readAllBytes(Paths.get(testFilePath)));
	expecteds =
		">seq1\n" +
		"AVGTACGTACGTACGTCATGCATGCATGCATGTAGCTAGCTAGCTAGC\n";
	assertEquals(expecteds, result);
	Files.deleteIfExists(Paths.get(testFilePath));
}
 
Example 9
Project: Meucci   File: Master.java   Source Code and License Vote up 5 votes
private static void deleteAll(int v, ArrayList<String> createdFiles)
throws IOException{
    /*
    v=0 elimina tutto
    v=1 lascia i .asm
    v=2 lascia i .o
    */
    for(String t:createdFiles){
        if(v!=1)
            Files.deleteIfExists(Paths.get(t+".asm"));
        if(v!=2)
            Files.deleteIfExists(Paths.get(t+".o"));
    }
}
 
Example 10
Project: V8LogScanner   File: V8LogFileConstructor.java   Source Code and License Vote up 5 votes
static void deleteLogFile(String fileName) {
    try {
        Files.deleteIfExists(Paths.get(fileName));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 11
Project: itweet-boot   File: StorageServiceImpl.java   Source Code and License Vote up 5 votes
@Override
public void deleteByRuleFilename(String ruleFilename,String filePath) {
    try {
        System.out.println(Paths.get(filePath).resolve(ruleFilename));
        Files.deleteIfExists(Paths.get(filePath).resolve(ruleFilename));
    } catch (IOException e) {
        e.printStackTrace();
    }
    documentRepository.deleteByRuleFilename(ruleFilename);
}
 
Example 12
Project: jdk8u-jdk   File: Test7029048.java   Source Code and License Vote up 4 votes
static void test7029048() throws IOException {
    String desc = null;
    for (LLP_VAR v : LLP_VAR.values()) {
        switch (v) {
            case LLP_SET_WITH_JVM:
                // copy the files into the directory structures
                copyFile(srcLibjvmSo, dstServerLibjvm);
                // does not matter if it is client or a server
                copyFile(srcLibjvmSo, dstClientLibjvm);
                desc = "LD_LIBRARY_PATH should be set";
                break;
            case LLP_SET_EMPTY_PATH:
                if (!dstClientDir.exists()) {
                    Files.createDirectories(dstClientDir.toPath());
                } else {
                    Files.deleteIfExists(dstClientLibjvm.toPath());
                }

                if (!dstServerDir.exists()) {
                    Files.createDirectories(dstServerDir.toPath());
                } else {
                    Files.deleteIfExists(dstServerLibjvm.toPath());
                }

                desc = "LD_LIBRARY_PATH should not be set";
                break;
            case LLP_SET_NON_EXISTENT_PATH:
                if (dstLibDir.exists()) {
                    recursiveDelete(dstLibDir);
                }
                desc = "LD_LIBRARY_PATH should not be set";
                break;
            default:
                throw new RuntimeException("unknown case");
        }

        /*
         * Case 1: set the server path
         */
        env.clear();
        env.put(LD_LIBRARY_PATH, dstServerDir.getAbsolutePath());
        run(env, v.value + 1, "Case 1: " + desc);

        /*
         * Case 2: repeat with client path
         */
        env.clear();
        env.put(LD_LIBRARY_PATH, dstClientDir.getAbsolutePath());
        run(env, v.value + 1, "Case 2: " + desc);

        if (isSolaris) {
            /*
             * Case 3: set the appropriate LLP_XX flag,
             * java64 -d64, LLP_64 is relevant, LLP_32 is ignored
             */
            env.clear();
            env.put(LD_LIBRARY_PATH_64, dstServerDir.getAbsolutePath());
            run(env, v.value + 1, "Case 3: " + desc);
        }
    }
    return;
}
 
Example 13
Project: openjdk-jdk10   File: ControlCharTest.java   Source Code and License Vote up 4 votes
@AfterClass
public void close() throws IOException {
    Files.deleteIfExists(output);
}
 
Example 14
Project: kafka-webview   File: ClusterConfigControllerTest.java   Source Code and License Vote up 4 votes
/**
 * Test updating existing ssl cluster, updating the KeyStore file only.
 * This should leave the truststore file/password as is.
 */
@Test
@Transactional
public void testPostUpdate_existingSslClusterUpdateKeyStore() throws Exception {
    // Create an existing cluster
    final Cluster originalCluster = clusterTestTools.createCluster("My New Cluster");
    originalCluster.setValid(true);
    originalCluster.setSslEnabled(true);
    originalCluster.setKeyStorePassword("DummyKeyStorePassword");
    originalCluster.setKeyStoreFile("Cluster.KeyStore.jks");
    originalCluster.setTrustStorePassword("DummyTrustStorePassword");
    originalCluster.setTrustStoreFile("Cluster.TrustStore.jks");
    clusterRepository.save(originalCluster);

    // Create dummy JKS files
    FileTestTools.createDummyFile(keyStoreUploadPath + originalCluster.getKeyStoreFile(), "KeyStoreFile");
    FileTestTools.createDummyFile(keyStoreUploadPath + originalCluster.getTrustStoreFile(), "TrustStoreFile");

    // Only update cluster name, brokers, keep SSL enabled, and KeyStore file + password
    final String expectedClusterName = "UpdatedClusterName" + System.currentTimeMillis();
    final String expectedBrokerHosts = "updatedHost:9092";

    final MockMultipartFile keyStoreUpload = new MockMultipartFile("keyStoreFile", "UpdatedKeyStoreFile".getBytes(Charsets.UTF_8));

    // Hit create page.
    mockMvc
        .perform(fileUpload("/configuration/cluster/update")
            .file(keyStoreUpload)
            .with(user(adminUserDetails))
            .with(csrf())
            .param("id", String.valueOf(originalCluster.getId()))
            .param("name", expectedClusterName)
            .param("brokerHosts", expectedBrokerHosts)
            .param("ssl", "true")
            .param("keyStorePassword", "NewPassword")
        )
        .andDo(print())
        .andExpect(status().is3xxRedirection())
        .andExpect(redirectedUrl("/configuration/cluster"));

    // Lookup Cluster
    final Cluster cluster = clusterRepository.findOne(originalCluster.getId());
    assertNotNull("Should have new cluster", cluster);
    assertEquals("Has correct name", expectedClusterName, cluster.getName());
    assertEquals("Has correct brokerHosts", expectedBrokerHosts, cluster.getBrokerHosts());
    assertEquals("Should be ssl enabled", true, cluster.isSslEnabled());
    assertEquals("Should not be valid by default", false, cluster.isValid());
    assertEquals("Password should be unchanged", "DummyTrustStorePassword", cluster.getTrustStorePassword());
    assertEquals("Should have trust store file path", "Cluster.TrustStore.jks", cluster.getTrustStoreFile());

    // trust store should remain
    final boolean doesTruststoreFileExist = Files.exists(Paths.get(keyStoreUploadPath, cluster.getTrustStoreFile()));
    assertTrue("TrustStore file should have been left untouched", doesTruststoreFileExist);
    final String trustStoreContents = FileTestTools.readFile(keyStoreUploadPath + cluster.getTrustStoreFile());
    assertEquals("TrustStore file should have remained untouched", "TrustStoreFile", trustStoreContents);

    // KeyStore was updated
    assertNotEquals("Password should be changed", "DummyKeyStorePassword", cluster.getKeyStorePassword());
    assertEquals("Should have key store file path", expectedClusterName + ".keystore.jks", cluster.getKeyStoreFile());

    final boolean doesKeyStoreFileExist = Files.exists(Paths.get(keyStoreUploadPath, cluster.getKeyStoreFile()));
    assertTrue("keyStore file should exist", doesKeyStoreFileExist);
    final String keyStoreContents = FileTestTools.readFile(keyStoreUploadPath + cluster.getKeyStoreFile());
    assertEquals("KeyStore file should have been updated", "UpdatedKeyStoreFile", keyStoreContents);

    // Cleanup
    Files.deleteIfExists(Paths.get(keyStoreUploadPath, cluster.getTrustStoreFile()));
    Files.deleteIfExists(Paths.get(keyStoreUploadPath, cluster.getKeyStoreFile()));
}
 
Example 15
Project: redirector   File: FilesPathHelperTest.java   Source Code and License Vote up 4 votes
@Before
public void setUp () throws URISyntaxException, IOException {
    String path = getCurrentPath();
    Files.deleteIfExists(Paths.get(path  + TMP_FILE));
}
 
Example 16
Project: httrack2warc   File: CdxWriter.java   Source Code and License Vote up 4 votes
@Override
public void close() throws IOException {
    writer.close();
    Files.deleteIfExists(tmpCdxPath);
}
 
Example 17
Project: hygene   File: SearchQueryTest.java   Source Code and License Vote up 4 votes
@AfterEach
void afterEach() throws IOException {
    Files.deleteIfExists(Paths.get(GFA_TEST_FILE + FileDatabaseDriver.DB_FILE_EXTENSION));
    Files.deleteIfExists(Paths.get(GFA_TEST_FILE + ".hygenecache"));
}
 
Example 18
Project: kafka-webview   File: MessageFormatController.java   Source Code and License Vote up 4 votes
/**
 * POST deletes the selected message format.
 */
@RequestMapping(path = "/delete/{id}", method = RequestMethod.POST)
public String deleteCluster(@PathVariable final Long id, final RedirectAttributes redirectAttributes) {
    // Where to redirect.
    final String redirectUrl = "redirect:/configuration/messageFormat";

    // Retrieve it
    final MessageFormat messageFormat = messageFormatRepository.findOne(id);
    if (messageFormat == null || messageFormat.isDefaultFormat()) {
        // Set flash message & redirect
        redirectAttributes.addFlashAttribute(
            "FlashMessage",
            FlashMessage.newWarning("Unable to remove message format!"));
        return redirectUrl;
    }
    // See if its in use by any views
    final Iterable<View> views = viewRepository
        .findAllByKeyMessageFormatIdOrValueMessageFormatIdOrderByNameAsc(messageFormat.getId(), messageFormat.getId());
    final Collection<String> viewNames = new ArrayList<>();
    for (final View view: views) {
        viewNames.add(view.getName());
    }
    if (!viewNames.isEmpty()) {
        // Set flash message & redirect
        redirectAttributes.addFlashAttribute(
            "FlashMessage",
            FlashMessage.newWarning("Message format in use by views: " + viewNames.toString()));
        return redirectUrl;
    }

    try {
        // Delete entity
        messageFormatRepository.delete(id);

        // Delete jar from disk
        try {
            Files.deleteIfExists(deserializerLoader.getPathForJar(messageFormat.getJar()));
        } catch (final NoSuchFileException exception) {
            // swallow.
        }
        redirectAttributes.addFlashAttribute(
            "FlashMessage",
            FlashMessage.newSuccess("Deleted message format!"));
    } catch (final IOException e) {
        redirectAttributes.addFlashAttribute(
            "FlashMessage",
            FlashMessage.newWarning("Unable to remove message format! " + e.getMessage()));
        return redirectUrl;
    }

    // redirect to cluster index
    return redirectUrl;
}
 
Example 19
Project: ARCLib   File: IngestWorkflowTest.java   Source Code and License Vote up 4 votes
@AfterClass
public static void afterClass() throws IOException {
    Files.deleteIfExists(QUARANTINE_FOLDER.resolve(CORRUPTED_FILE_NAME));
    Files.deleteIfExists(QUARANTINE_FOLDER.resolve(CORRUPTED_FILE_NAME2));
}
 
Example 20
Project: neoscada   File: Processor.java   Source Code and License Vote up 4 votes
private void mirrorArtifact ( final IArtifactKey art, final Path versionBase, final MavenReference ref, final IProgressMonitor pm ) throws Exception
{
    if ( this.dryRun )
    {
        return;
    }

    final Path jarFile = versionBase.resolve ( ref.toFileName () );
    System.out.format ( "Storing to: %s%n", jarFile );

    if ( this.scrubJars && ref.getClassifier () == null )
    {
        final Path tmp = Files.createTempFile ( null, ".jar" );
        try
        {
            fetchArtifact ( art, pm, tmp );
            try ( JarInputStream jin = new JarInputStream ( Files.newInputStream ( tmp ) );
                  JarOutputStream jout = new JarOutputStream ( Files.newOutputStream ( jarFile ), jin.getManifest () ); )
            {
                JarEntry entry;
                while ( ( entry = jin.getNextJarEntry () ) != null )
                {
                    final String name = entry.getName ();
                    if ( name.startsWith ( "META-INF/maven/" ) )
                    {
                        System.out.format ( "Scrubbing Maven information: %s%n", name );
                        continue;
                    }
                    jout.putNextEntry ( entry );
                    ByteStreams.copy ( jin, jout );
                }
            }
        }
        finally
        {
            Files.deleteIfExists ( tmp );
        }
    }
    else
    {
        fetchArtifact ( art, pm, jarFile );
    }

    makeChecksum ( "MD5", jarFile, versionBase.resolve ( ref.toFileName ( "md5" ) ) );
    makeChecksum ( "SHA1", jarFile, versionBase.resolve ( ref.toFileName ( "sha1" ) ) );
}