All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.conqat.lib.commons.filesystem.TemporaryDirectory Maven / Gradle / Ivy

There is a newer version: 2024.7.2
Show newest version
/*
 * 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);
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy