Java Code Examples for org.apache.commons.io.FileUtils.forceDelete()

The following are Jave code examples for showing how to use forceDelete() of the org.apache.commons.io.FileUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: launcher-backend   File: GitHubServiceIT.java   View Source Code Vote up 6 votes
@Test
public void createGitHubRepositoryWithContent() throws Exception {
    // given
    final String repositoryName = generateRepositoryName();
    Path tempDirectory = Files.createTempDirectory("test");
    Path file = tempDirectory.resolve("README.md");
    Files.write(file, Collections.singletonList("Read me to know more"), Charset.forName("UTF-8"));

    // when
    final GitRepository targetRepo = getGitHubService().createRepository(repositoryName, MY_GITHUB_REPO_DESCRIPTION);
    getGitHubService().push(targetRepo, tempDirectory.toFile());

    // then
    Assert.assertEquals(GitHubTestCredentials.getUsername() + "/" + repositoryName, targetRepo.getFullName());
    URI readmeUri = UriBuilder.fromUri("https://raw.githubusercontent.com/")
            .path(GitHubTestCredentials.getUsername())
            .path(repositoryName)
            .path("/master/README.md").build();
    HttpURLConnection connection = (HttpURLConnection) readmeUri.toURL().openConnection();
    Assert.assertEquals("README.md should have been pushed to the repo", 200, connection.getResponseCode());

    FileUtils.forceDelete(tempDirectory.toFile());
}
 
Example 2
Project: monarch   File: KDCQuasiService.java   View Source Code Vote up 6 votes
private void cleanUpDir() {
  try {
    LOG.info("Deleting Keytab dir. " + this.getKeyTabDir());
    File keytabDir = new File(this.getKeyTabDir());
    if (keytabDir.exists()) {
      FileUtils.forceDelete(keytabDir);
    }
    File kdcWorkDir = new File(this.kdc_work_dir);
    LOG.info("Deleting KDC temporary dir. " + kdcWorkDir);
    if (kdcWorkDir.exists()) {
      FileUtils.forceDelete(kdcWorkDir);
    }
  } catch (IOException ex) {
    LOG.error("Couldn't delete work dir");
  }
}
 
Example 3
Project: argument-reasoning-comprehension-task   File: CompressedXmiWriter.java   View Source Code Vote up 6 votes
private void addSingleEntryToTar(byte[] singleEntryContent, String singleEntryName)
        throws IOException
{
    // create new entry; it requires file for some reasons...
    File tmpFile = File.createTempFile("temp", "bin");
    OutputStream os = new FileOutputStream(tmpFile);
    IOUtils.write(singleEntryContent, os);

    TarArchiveEntry tarEntry = new TarArchiveEntry(tmpFile, singleEntryName);
    outputStream.putArchiveEntry(tarEntry);

    // copy streams
    IOUtils.copy(new ByteArrayInputStream(singleEntryContent), outputStream);
    outputStream.closeArchiveEntry();

    // delete the temp file
    FileUtils.forceDelete(tmpFile);
}
 
Example 4
Project: WeiMusicCommunity-server   File: CommityManageService.java   View Source Code Vote up 6 votes
public void editCommityInfo(CommityInfo info, String lastPath) throws IOException {
    //检查图像有没有变化
    if (!(info.getCHeadImg().equals(lastPath))) {
        //删除之前的图
        FileUtils.forceDelete(new File(StaticVar.getToFilePath() + lastPath));
        //存新图
        String fileName = new File(info.getCHeadImg()).getName();
        String filePathStr = "CommitySpace/" + info.getCid() + "/" + fileName;

        File tarNewFile = new File(StaticVar.getToFilePath() + filePathStr);
        FileUtils.writeByteArrayToFile(tarNewFile, info.getCImgObj().getBytes(StaticVar.getDecodeFileSet()));
        info.setCHeadImg(filePathStr);
    }
    commityManageDao.editCommityInfo(info);

}
 
Example 5
Project: dependency-loader   File: Xmls.java   View Source Code Vote up 6 votes
/**
 * Reads the Latest Snapshot version from a Meta file, and then deletes it
 *
 * @param dependency The dependency
 * @param metaFile The Meta file
 *
 * @return The version with "SNAPSHOT" replaced with the latest
 */
@SuppressWarnings("WeakerAccess")
public static @NotNull String readLatestSnapshot(@NotNull Dependency dependency, @NotNull File metaFile) {
	try {
		final Element document = readDocument(metaFile);

		Element snapshot = (Element) document.getElementsByTagName("snapshot").item(0);

		final String timestamp   = readTag(snapshot, "timestamp");
		final String buildNumber = readTag(snapshot, "buildNumber");

		final String latestSnapshot = dependency.getVersion().replace("SNAPSHOT", timestamp + "-" + buildNumber);
		DLoader.debug("Latest Snapshot version of " + dependency.getName() + " is " + latestSnapshot);

		FileUtils.forceDelete(metaFile);

		return latestSnapshot;

	} catch (Exception e) {
		DLoader.log(Level.SEVERE, "Failed to load meta for snapshot of  " + dependency);
		e.printStackTrace();
	}

	return "ERROR";
}
 
Example 6
Project: Reer   File: OutputPreparingTaskOutputPacker.java   View Source Code Vote up 5 votes
@Override
public void unpack(TaskOutputsInternal taskOutputs, InputStream input, TaskOutputOriginReader readOrigin) {
    for (TaskOutputFilePropertySpec propertySpec : taskOutputs.getFileProperties()) {
        CacheableTaskOutputFilePropertySpec property = (CacheableTaskOutputFilePropertySpec) propertySpec;
        File output = property.getOutputFile();
        if (output == null) {
            continue;
        }
        try {
            switch (property.getOutputType()) {
                case DIRECTORY:
                    makeDirectory(output);
                    FileUtils.cleanDirectory(output);
                    break;
                case FILE:
                    if (!makeDirectory(output.getParentFile())) {
                        if (output.exists()) {
                            FileUtils.forceDelete(output);
                        }
                    }
                    break;
                default:
                    throw new AssertionError();
            }
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
    delegate.unpack(taskOutputs, input, readOrigin);
}
 
Example 7
Project: WeiMusicCommunity-server   File: ProjectService.java   View Source Code Vote up 5 votes
public void delFileOldest(ProjectFile file) throws IOException {
    //1.查出最老的文件路径
    ProjectFile oldest = projectDao.getOldestFile(file);
    //2.删除当前文件
    FileUtils.forceDelete(new File(StaticVar.getToFilePath() + oldest.getPFPath()));
    //3 数据库删除这个记录
    projectDao.delOldest(oldest);
}
 
Example 8
Project: Reer   File: GFileUtils.java   View Source Code Vote up 5 votes
public static void forceDelete(File file) {
    try {
        FileUtils.forceDelete(file);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 9
Project: distmq   File: Segment.java   View Source Code Vote up 5 votes
public void delete() {
    close();
    String fullFileName = dirName + File.separator + fileName;
    File file = new File(fullFileName);
    try {
        FileUtils.forceDelete(file);
    } catch (IOException ex) {
        LOG.warn("delete file exception:", ex);
    }
}
 
Example 10
Project: Open_Source_ECOA_Toolset_AS5   File: GenerationUtils.java   View Source Code Vote up 5 votes
public static void clearCreatedFolders(File root) {
	File[] files = root.listFiles();
	try {
		for (File file : files) {
			if (file.getName().equalsIgnoreCase("output")) {
				FileUtils.deleteDirectory(file);
			}
			if (file.getName().equalsIgnoreCase("4-ComponentImplementations")) {
				File[] child = file.listFiles();
				for (File c : child) {
					if (c.isFile())
						FileUtils.forceDelete(c);
					else {
						File[] gChild = c.listFiles();
						for (File gC : gChild) {
							if (gC.isDirectory())
								FileUtils.deleteDirectory(gC);
							else if (!StringUtils.endsWith(gC.getName(), ".impl.xml"))
								FileUtils.forceDelete(gC);
						}
					}
				}
			}
		}
	} catch (IOException e) {
		System.out.println(e);
	}
}
 
Example 11
Project: fastdfs-quickstart   File: SimpleJsonFileUploadProcessor.java   View Source Code Vote up 5 votes
@Override
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public FResult<JSONObject> process(UploadRequest request) throws Exception {
  Long commonFileId = null;
  try {
    File temporaryFile = new File(request.getTemporaryFilePath());
    if (temporaryFile == null || !temporaryFile.isFile() || !temporaryFile.exists()) {
      return FResult.newFailure(HttpResponseCode.SERVER_IO_READ, "上传失败");
    }
    String currentFileMd5 = request.getTemporaryFileMd5();
    String fileId = uploadFileReturnFileId(request.getTemporaryFilePath(), request.getSuffix());
    if (StringUtils.isBlank(fileId)) {
      return FResult.newFailure(HttpResponseCode.SERVER_IO_WRITE, "上传文件到FastDFS失败,请检查FastDFS日志");
    }
    long nowTimestamp = System.currentTimeMillis();
    // 要保存的对象
    UploadFile commonFile = new UploadFile();
    commonFile.setFilemd5(currentFileMd5);
    // 保存主文件后,返回住表ID
    log.debug("你可以控制是否要持久化这个文件");
    commonFileId = commonFileService.addUploadFile(nowTimestamp, commonFile, temporaryFile, request, fileId);
    if (commonFileId == null || commonFileId == 0) {
      log.error("insert common_file failed,record:" + JSON.toJSONString(commonFile));
      FileUtils.forceDelete(temporaryFile);
      return FResult.newFailure(HttpResponseCode.SERVER_DB_ERROR, "保存上传记录失败");
    }
    return buildResult(request.getOriginalFilename(), request.getTemporaryFileSize(), request.getTemporaryFileMd5(), commonFile.getUrl(),
        commonFile.getId());
  } catch (Exception uploadException) {
    log.error("普通文件上传过程中发生错误", uploadException);
    return FResult.newFailure(HttpResponseCode.SERVER_ERROR, "文件上传过程中发生错误");
  }
}
 
Example 12
Project: flume-release-1.7.0   File: TestHeaderAndBodyTextEventSerializer.java   View Source Code Vote up 5 votes
@Test
public void testNoNewline() throws FileNotFoundException, IOException {

  Map<String, String> headers = new HashMap<String, String>();
  headers.put("header1", "value1");
  headers.put("header2", "value2");

  OutputStream out = new FileOutputStream(testFile);
  Context context = new Context();
  context.put("appendNewline", "false");
  EventSerializer serializer =
      EventSerializerFactory.getInstance("header_and_text", context, out);
  serializer.afterCreate();
  serializer.write(EventBuilder.withBody("event 1\n", Charsets.UTF_8, headers));
  serializer.write(EventBuilder.withBody("event 2\n", Charsets.UTF_8, headers));
  serializer.write(EventBuilder.withBody("event 3\n", Charsets.UTF_8, headers));
  serializer.flush();
  serializer.beforeClose();
  out.flush();
  out.close();

  BufferedReader reader = new BufferedReader(new FileReader(testFile));
  Assert.assertEquals("{header2=value2, header1=value1} event 1", reader.readLine());
  Assert.assertEquals("{header2=value2, header1=value1} event 2", reader.readLine());
  Assert.assertEquals("{header2=value2, header1=value1} event 3", reader.readLine());
  Assert.assertNull(reader.readLine());
  reader.close();

  FileUtils.forceDelete(testFile);
}
 
Example 13
Project: osc-core   File: SslCertificateUploader.java   View Source Code Vote up 5 votes
protected void removeUploadedFile() {
    if (this.file != null && this.file.exists()) {
        try {
            FileUtils.forceDelete(this.file);
        } catch (IOException e) {
            log.error("Deleting ssl certificate file: " + this.file + " failed when upload was cancelled by user.", e);
        }
    }
}
 
Example 14
Project: Open_Source_ECOA_Toolset_AS5   File: ExportCommand.java   View Source Code Vote up 5 votes
private File createFile(String loc, boolean delete) throws IOException {
	File file = new File(loc);
	if (delete && file.exists())
		FileUtils.forceDelete(file);
	file.getParentFile().mkdirs();
	file.createNewFile();
	return file;
}
 
Example 15
Project: spring2ts   File: SourceGen.java   View Source Code Vote up 5 votes
private void cleanOutputDir() throws IOException {
    if(outputDir.exists() && !outputDir.isDirectory()) {
        throw new IllegalStateException(outputDir.getAbsolutePath() + " is not a directory!");
    }

    if(outputDir.exists()) {
        FileUtils.forceDelete(outputDir);
    }
    FileUtils.forceMkdir(outputDir);
}
 
Example 16
Project: jfrog-idea-plugin   File: NpmScanManagerTests.java   View Source Code Vote up 5 votes
@AfterClass
public void cleanProject() {
    try {
        Path installationDirectory = Paths.get(getProjectBasePath(project), ".idea");
        if (Files.exists(installationDirectory)) {
            FileUtils.forceDelete(installationDirectory.toFile());
        }
    } catch (IOException e) {
        // Ignore
    }
}
 
Example 17
Project: flume-release-1.7.0   File: TestFlumeEventAvroEventSerializer.java   View Source Code Vote up 5 votes
public void createAvroFile(File file, String codec) throws FileNotFoundException, IOException {

    if (file.exists()) {
      FileUtils.forceDelete(file);
    }

    // serialize a few events using the reflection-based avro serializer
    OutputStream out = new FileOutputStream(file);

    Context ctx = new Context();
    if (codec != null) {
      ctx.put("compressionCodec", codec);
    }

    EventSerializer.Builder builder =
        new FlumeEventAvroEventSerializer.Builder();
    EventSerializer serializer = builder.build(ctx, out);

    serializer.afterCreate();
    serializer.write(EventBuilder.withBody("yo man!", Charsets.UTF_8));
    serializer.write(EventBuilder.withBody("2nd event!", Charsets.UTF_8));
    serializer.write(EventBuilder.withBody("last one!", Charsets.UTF_8));
    serializer.flush();
    serializer.beforeClose();
    out.flush();
    out.close();
  }
 
Example 18
Project: VASSAL-src   File: TempFileManager.java   View Source Code Vote up 4 votes
private void cleanupSessionRoot() throws IOException {
  if (lock.exists()) FileUtils.forceDelete(lock);
  FileUtils.forceDelete(sessionRoot);
}
 
Example 19
Project: NanoMaven   File: NanoTempFile.java   View Source Code Vote up 4 votes
@Override
public void delete() throws Exception {
    IOUtils.closeQuietly(outputStream);
    FileUtils.forceDelete(file);
}
 
Example 20
Project: Hydroangeas   File: MinecraftServerC.java   View Source Code Vote up 4 votes
public boolean startServer()
{
    try
    {
        JsonObject startupOptionsObj = startupOptions.getAsJsonObject();
        String maxRAM = startupOptionsObj.get("maxRAM").getAsString();

        container = new DockerContainer(
                getServerName(),
                serverFolder,
                port,
                new String[]{"/usr/bin/java",
                        //"-Duser.dir " + serverFolder.getAbsolutePath(),
                        "-Xmx" + maxRAM,
                        "-Xms" + startupOptionsObj.get("minRAM").getAsString(),
                        "-Xmn" + startupOptionsObj.get("edenRAM").getAsString(),
                        "-XX:+UseG1GC",
                        "-XX:+UnlockExperimentalVMOptions",
                        "-XX:MaxGCPauseMillis=50",
                        "-XX:+DisableExplicitGC",
                        "-XX:G1HeapRegionSize=4M",
                        "-XX:TargetSurvivorRatio=90",
                        "-XX:G1NewSizePercent=50",
                        "-XX:G1MaxNewSizePercent=80",
                        "-XX:InitiatingHeapOccupancyPercent=10",
                        "-XX:G1MixedGCLiveThresholdPercent=50",
                        "-XX:+AggressiveOpts",
                        "-XX:+UseLargePagesInMetaspace",
                        "-Djava.net.preferIPv4Stack=true",
                        "-Dcom.sun.management.jmxremote",
                        "-Dcom.sun.management.jmxremote.port=" + (getPort()+1),
                        "-Dcom.sun.management.jmxremote.local.only=false",
                        "-Dcom.sun.management.jmxremote.authenticate=false",
                        "-Dcom.sun.management.jmxremote.ssl=false",
                        "-jar", serverFolder.getAbsolutePath()+"/spigot.jar", "nogui"},
                maxRAM
        );
        Hydroangeas.getLogger().info(container.createContainer());

        getLogger().info("Starting server " + getServerName());

        remoteControl = new RemoteControl(this, "blackmesa", (getPort()+1));
    } catch (Exception e)
    {
        this.instance.log(Level.SEVERE, "Can't start the server " + getServerName() + "!");
        e.printStackTrace();
        try
        {
            FileDeleteStrategy.FORCE.delete(serverFolder);
            FileUtils.forceDelete(serverFolder);
        } catch (IOException e1)
        {
        }

        return false;
    }

    return true;
}