1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.configuration2;
19
20 import java.io.File;
21 import java.io.IOException;
22 import java.nio.file.Files;
23
24 import org.junit.jupiter.api.io.TempDir;
25
26 /**
27 * A utility class to make working with {@link TempDir} easier.
28 * It encapsulates some of the functionality from JUnit 4's {@code TemporaryFolder} class.
29 */
30 public final class TempDirUtils {
31
32 private static final String TMP_PREFIX = "junit";
33
34 private TempDirUtils() {
35 }
36
37 /**
38 * Returns a new fresh file with a random name under a temporary folder.
39 *
40 * @param tempFolder the temporary folder to create the file under
41 * @return the created file
42 * @throws IOException if an error occurs
43 */
44 public static File newFile(final File tempFolder) throws IOException {
45 return Files.createTempFile(tempFolder.toPath(), TMP_PREFIX, null).toFile();
46 }
47
48 /**
49 * Returns a new fresh file with the given name under a temporary folder.
50 *
51 * @param tempFolder the temporary folder to create the file under
52 * @return the created file
53 * @throws IOException if an error occurs
54 */
55 public static File newFile(final String fileName, final File tempFolder) throws IOException {
56 return Files.createFile(tempFolder.toPath().resolve(fileName)).toFile();
57 }
58
59 /**
60 * Returns a new fresh folder with a random name under a temporary folder.
61 *
62 * @param tempFolder the temporary folder to create the folder under
63 * @return the created folder
64 * @throws IOException if an error occurs
65 */
66 public static File newFolder(final File tempFolder) throws IOException {
67 return Files.createTempDirectory(tempFolder.toPath(), TMP_PREFIX).toFile();
68 }
69
70 /**
71 * Returns a new fresh folder with the given path under a temporary folder.
72 *
73 * @param tempFolder the temporary folder to create the folder under
74 * @return the created folder
75 * @throws IOException if an error occurs
76 */
77 public static File newFolder(final String path, final File tempFolder) throws IOException {
78 return Files.createDirectory(tempFolder.toPath().resolve(path)).toFile();
79 }
80 }