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

The following examples show how to use java.nio.file.Files#deleteIfExists() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestFileSystem.java    From jsr203-hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testCopyAndMoveFiles() throws IOException {
  URI uriSrc = clusterUri.resolve("/tmp/testSrcFile");
  Path pathSrc = Paths.get(uriSrc);

  URI uriDstCp = clusterUri.resolve("/tmp/testDstCopyFile");
  Path pathDstCp = Paths.get(uriDstCp);

  OutputStream os = Files.newOutputStream(pathSrc);
  os.write("write \n several \n things\n".getBytes());
  os.close();
  Files.copy(pathSrc, pathDstCp);
  assertTrue(Files.exists(pathDstCp));
  assertEquals(Files.size(pathSrc), Files.size(pathDstCp));

  URI uriDstMv = clusterUri.resolve("/tmp/testDstMoveFile");
  Path pathDstMv = Paths.get(uriDstMv);
  Files.move(pathDstCp, pathDstMv);
  assertFalse(Files.exists(pathDstCp));// move from
  assertTrue(Files.exists(pathDstMv));// move to
  assertEquals(Files.size(pathSrc), Files.size(pathDstMv));
  Files.deleteIfExists(pathSrc);
  Files.deleteIfExists(pathDstMv);
}
 
Example 2
Source File: Main.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Outputs the class index table to the INDEX.LIST file of the
 * root jar file.
 */
void dumpIndex(String rootjar, JarIndex index) throws IOException {
    File jarFile = new File(rootjar);
    Path jarPath = jarFile.toPath();
    Path tmpPath = createTempFileInSameDirectoryAs(jarFile).toPath();
    try {
        if (update(Files.newInputStream(jarPath),
                   Files.newOutputStream(tmpPath),
                   null, index)) {
            try {
                Files.move(tmpPath, jarPath, REPLACE_EXISTING);
            } catch (IOException e) {
                throw new IOException(getMsg("error.write.file"), e);
            }
        }
    } finally {
        Files.deleteIfExists(tmpPath);
    }
}
 
Example 3
Source File: CompletionSuggestionTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test(enabled = false) //TODO 8171829
public void testBrokenClassFile2() throws IOException {
    Path broken = outDir.resolve("broken");
    compiler.compile(broken,
            "package p;\n" +
            "public class BrokenA {\n" +
            "}",
            "package p.q;\n" +
            "public class BrokenB {\n" +
            "}",
            "package p;\n" +
            "public class BrokenC {\n" +
            "}");
    Path cp = compiler.getPath(broken);
    Path target = cp.resolve("p").resolve("BrokenB.class");
    Files.deleteIfExists(target);
    Files.move(cp.resolve("p").resolve("q").resolve("BrokenB.class"), target);
    addToClasspath(cp);

    assertEval("import p.*;");
    assertCompletion("Broke|", "BrokenA", "BrokenC");
}
 
Example 4
Source File: KtabZero.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        // 0. Non-existing keytab
        Files.deleteIfExists(Paths.get(NAME));
        check(true);

        // 1. Create with KeyTab
        Files.deleteIfExists(Paths.get(NAME));
        KeyTab.getInstance(NAME).save();
        check(false);

        // 2. Create with the tool
        Files.deleteIfExists(Paths.get(NAME));
        try {
            Class ktab = Class.forName("sun.security.krb5.internal.tools.Ktab");
            ktab.getDeclaredMethod("main", String[].class).invoke(null,
                    (Object)(("-k " + NAME + " -a me@HERE pass").split(" ")));
        } catch (ClassNotFoundException cnfe) {
            // Only Windows has ktab tool
            System.out.println("No ktab tool here. Ignored.");
            return;
        }
        check(false);
    }
 
Example 5
Source File: PingRequestHandler.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected void handleEnable(boolean enable) throws SolrException {
  if (healthcheck == null) {
    throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, 
      "No healthcheck file defined.");
  }
  if ( enable ) {
    try {
      // write out when the file was created
      FileUtils.write(healthcheck, Instant.now().toString(), "UTF-8");
    } catch (IOException e) {
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, 
                              "Unable to write healthcheck flag file", e);
    }
  } else {
    try {
      Files.deleteIfExists(healthcheck.toPath());
    } catch (Throwable cause) {
      throw new SolrException(SolrException.ErrorCode.NOT_FOUND,
                              "Did not successfully delete healthcheck file: "
                              +healthcheck.getAbsolutePath(), cause);
    }
  }
}
 
Example 6
Source File: BinaryPipeline.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
public void build(Path target, boolean deleteTempFiles) throws IOException {
    LogHelper.info("Building launcher binary file");
    count.set(0); // set jar number
    Path thisPath = null;
    boolean isNeedDelete = false;
    long time_start = System.currentTimeMillis();
    long time_this = time_start;
    for (LauncherBuildTask task : tasks) {
        LogHelper.subInfo("Task %s", task.getName());
        Path oldPath = thisPath;
        thisPath = task.process(oldPath);
        long time_task_end = System.currentTimeMillis();
        long time_task = time_task_end - time_this;
        time_this = time_task_end;
        if (isNeedDelete && deleteTempFiles) Files.deleteIfExists(oldPath);
        isNeedDelete = task.allowDelete();
        LogHelper.subInfo("Task %s processed from %d millis", task.getName(), time_task);
    }
    long time_end = System.currentTimeMillis();
    if (isNeedDelete && deleteTempFiles) IOHelper.move(thisPath, target);
    else IOHelper.copy(thisPath, target);
    LogHelper.info("Build successful from %d millis", time_end - time_start);
}
 
Example 7
Source File: JoalConfigProviderTest.java    From joal with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldWriteConfigurationFile() throws IOException {
    new ObjectMapper().writeValue(rewritableJoalFoldersPath.getConfPath().resolve("config.json").toFile(), defaultConfig);
    try {
        final JoalConfigProvider provider = new JoalConfigProvider(new ObjectMapper(), rewritableJoalFoldersPath, Mockito.mock(ApplicationEventPublisher.class));
        final Random rand = new Random();
        final AppConfiguration newConf = new AppConfiguration(
                rand.longs(1, 200).findFirst().getAsLong(),
                rand.longs(201, 400).findFirst().getAsLong(),
                rand.ints(1, 5).findFirst().getAsInt(),
                RandomStringUtils.random(60),
                false
        );

        provider.saveNewConf(newConf);

        assertThat(provider.loadConfiguration()).isEqualTo(newConf);
    } finally {
        Files.deleteIfExists(rewritableJoalFoldersPath.getConfPath().resolve("config.json"));
    }
}
 
Example 8
Source File: CommonHelper.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private synchronized static RecordedEvent getTimeStampCounterEvent() throws IOException, Exception {
    if (timeStampCounterEvent == null) {
        try (Recording r = new Recording()) {
            r.enable("com.oracle.jdk.CPUTimeStampCounter");
            r.start();
            r.stop();
            Path p = Files.createTempFile("timestamo", ".jfr");
            r.dump(p);
            List<RecordedEvent> events = RecordingFile.readAllEvents(p);
            Files.deleteIfExists(p);
            if (events.isEmpty()) {
                throw new Exception("Could not locate CPUTimeStampCounter event");
            }
            timeStampCounterEvent = events.get(0);
        }
    }
    return timeStampCounterEvent;
}
 
Example 9
Source File: JImageVerifyTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testVerifyNotExistingImage() throws IOException {
    Path tmp = Paths.get(".", "not_existing_image");
    Files.deleteIfExists(tmp);
    jimage("verify", "")
            .assertFailure()
            .assertShowsError();
}
 
Example 10
Source File: OpenfireX509TrustManagerTest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() throws Exception
{
    // Attempt to delete any left-overs from the test.
    validChain = null;

    if ( trustStore != null)
    {
        trustStore = null;
        Files.deleteIfExists( Paths.get( location ) );
    }

    systemUnderTest = null;
}
 
Example 11
Source File: SegmentTableTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test table with an on-disk segment store that is lazy loaded in the table
 *
 * @throws IOException
 *             when creating the segment store
 */
@Test
public void onDiskSegStoreTest() throws IOException {
    Path segmentFile = Files.createTempFile("tmpSegStore", ".tmp");
    assertNotNull(segmentFile);
    ISegmentStore<@NonNull BasicSegment> fixture = null;
    try {
        final int size = 1000000;
        fixture = SegmentStoreFactory.createOnDiskSegmentStore(segmentFile, BasicSegment.BASIC_SEGMENT_READ_FACTORY, 1);
        for (int i = 0; i < size; i++) {
            fixture.add(new BasicSegment(i, 2 * i));
        }
        fixture.close(false);
        assertNotNull(getTable());
        getTable().updateModel(fixture);
        SWTBotTable tableBot = new SWTBotTable(getTable().getTableViewer().getTable());
        fBot.waitUntil(ConditionHelpers.isTableCellFilled(tableBot, "0", 0, 2));
        tableBot.header("Duration").click();
        fBot.waitUntil(ConditionHelpers.isTableCellFilled(tableBot, "0", 0, 2));
        tableBot.header("Duration").click();
        fBot.waitUntil(ConditionHelpers.isTableCellFilled(tableBot, "999,999", 0, 2));
    } finally {
        if (fixture != null) {
            fixture.close(true);
        }
        Files.deleteIfExists(segmentFile);
    }
}
 
Example 12
Source File: FileSystemProcessInstances.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(String id) {
    Path processInstanceStorage = Paths.get(storage.toString(), resolveId(id));

    try {
        Files.deleteIfExists(processInstanceStorage);
    } catch (IOException e) {
        throw new RuntimeException("Unable to remove process instance with id " + id, e);
    }

}
 
Example 13
Source File: AwsSnsTestBase.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
static void clear() {
    File out = new File("target/test-classes/META-INF/microprofile-config.properties");
    try {
        Files.deleteIfExists(out.toPath());
    } catch (IOException e) {
        LOGGER.error("Unable to delete {}", out, e);
    }
}
 
Example 14
Source File: FileUtil.java    From pdown-core with MIT License 5 votes vote down vote up
/**
 * 创建指定大小的Sparse File
 */
public static void createFileWithSparse(String filePath, long length) throws IOException {
  Path path = Paths.get(filePath);
  try {
    Files.deleteIfExists(path);
    try (
        SeekableByteChannel channel = Files.newByteChannel(path, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, StandardOpenOption.SPARSE)
    ) {
      channel.position(length - 1);
      channel.write(ByteBuffer.wrap(new byte[]{0}));
    }
  } catch (IOException e) {
    throw new IOException("create spares file fail,path:" + filePath + " length:" + length, e);
  }
}
 
Example 15
Source File: LocalConfigStorageTest.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Test
public void testReading() throws IOException {
    final Path destination = Files.createTempFile("test-", "file");
    final File destinationFile = destination.toFile();

    try {
        try (BufferedWriter writer = Files.newBufferedWriter(destination)) {
            writer.write(TEST_STRING);
        }
        String read = FileUtils.readFromFile(destinationFile);
        assertEquals(TEST_STRING, read);
    } finally {
        Files.deleteIfExists(destination);
    }
}
 
Example 16
Source File: AbnormalAnalyzerAppModuleTest.java    From AisAbnormal with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void canProvideCsvEventRepository() throws IOException {
    Files.deleteIfExists(Paths.get("events.csv"));
    configuration.addProperty(CONFKEY_EVENTS_REPOSITORY_TYPE, "csv");
    configuration.addProperty(CONFKEY_EVENTS_CSV_FILE, "events.csv");
    assertEquals(CsvEventRepository.class, sut.provideEventRepository().getClass());
}
 
Example 17
Source File: ElytronModelControllerClientTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testElytronAdminConfig() throws Exception {
    Assert.assertNotNull("Could not find test-wildfly-config.xml", WILDFLY_CONFIG);
    final Path copiedConfig = configureElytron();
    // Start the server
    CONTROLLER.start(copiedConfig.getFileName().toString(), WILDFLY_CONFIG.toURI());

    testConnection();

    // Stop the container, then remove the copied config
    CONTROLLER.stop();
    Files.deleteIfExists(copiedConfig);
}
 
Example 18
Source File: ValidateAvroSchema.java    From arvo2parquet with MIT License 5 votes vote down vote up
public static void bytecodePatchAvroSchemaClass(final File avroSchemaClassesDir) throws ClassNotFoundException, IOException {
  final String avroSchemaClassPackageName = "org.apache.avro";
  final String avroSchemaFullClassName = avroSchemaClassPackageName + ".Schema";
  final String relativeFilePath = getClassRelativeFilePath(avroSchemaClassPackageName, avroSchemaFullClassName);
  final File clsFile = new File(avroSchemaClassesDir, relativeFilePath);
  Files.deleteIfExists(clsFile.toPath());
  final Class<?>[] methArgTypesMatch = { String.class };
  final DynamicType.Unloaded<?> avroSchemaClsUnloaded = new ByteBuddy()
          .rebase(Class.forName(avroSchemaFullClassName))
          .method(named("validateName").and(returns(String.class)).and(takesArguments(methArgTypesMatch))
                  .and(isPrivate()).and(isStatic()))
          .intercept(MethodDelegation.to(AvroSchemaInterceptor.class))
          .make();
  avroSchemaClsUnloaded.saveIn(avroSchemaClassesDir);
}
 
Example 19
Source File: LoggingOperationsSubsystemTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static Path createLogFile(final String filename) throws IOException {
    final Path logFile = logDir.resolve(filename);
    Files.deleteIfExists(logFile);
    return logFile;
}
 
Example 20
Source File: CsvOutputFormatTest.java    From flink with Apache License 2.0 4 votes vote down vote up
@After
public void cleanUp() throws IOException {
	Files.deleteIfExists(Paths.get(path));
}