org.conqat.lib.commons.filesystem.TemporaryDirectory Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of teamscale-lib-commons Show documentation
Show all versions of teamscale-lib-commons Show documentation
Provides common utility functions
/*
* Copyright (c) CQSE GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.conqat.lib.commons.filesystem;
import static org.conqat.lib.commons.filesystem.FileSystemUtils.ensureDirectoryExists;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
/** Creates a {@link Path} when created and deletes it when closed. */
public class TemporaryDirectory implements AutoCloseable {
private final Path path;
private final boolean keepUntilShutdown;
/**
* Use {@link FileSystemUtils#getTemporaryDirectory} or
* {@link FileSystemUtils#getTemporaryDirectoryDeletedOnShutdown} to create an instance of this
* class.
*/
/* package */ TemporaryDirectory(Path path, boolean keepUntilShutdown) throws IOException {
this.path = path;
this.keepUntilShutdown = keepUntilShutdown;
ensureDirectoryExists(path);
if (keepUntilShutdown) {
deleteOnShutdown(path);
}
}
public Path getPath() {
return path;
}
@Override
public void close() throws IOException {
if (keepUntilShutdown) {
return;
}
delete(path);
}
private static void deleteOnShutdown(Path path) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
delete(path);
} catch (IOException e) {
// Can not do anything about this.
}
}));
}
private static void delete(Path path) throws IOException {
if (!Files.exists(path)) {
return;
}
if (Files.isDirectory(path)) {
FileSystemUtils.deleteRecursively(path);
} else {
Files.delete(path);
}
}
}