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 /**
35 * Returns a new fresh file with a random name under a temporary folder.
36 *
37 * @param tempFolder the temporary folder to create the file under
38 * @return the created file
39 * @throws IOException if an error occurs
40 */
41 public static File newFile(final File tempFolder) throws IOException {
42 return Files.createTempFile(tempFolder.toPath(), TMP_PREFIX, null).toFile();
43 }
44
45 /**
46 * Returns a new fresh file with the given name under a temporary folder.
47 *
48 * @param tempFolder the temporary folder to create the file under
49 * @return the created file
50 * @throws IOException if an error occurs
51 */
52 public static File newFile(final String fileName, final File tempFolder) throws IOException {
53 return Files.createFile(tempFolder.toPath().resolve(fileName)).toFile();
54 }
55
56 /**
57 * Returns a new fresh folder with a random name under a temporary folder.
58 *
59 * @param tempFolder the temporary folder to create the folder under
60 * @return the created folder
61 * @throws IOException if an error occurs
62 */
63 public static File newFolder(final File tempFolder) throws IOException {
64 return Files.createTempDirectory(tempFolder.toPath(), TMP_PREFIX).toFile();
65 }
66
67 /**
68 * Returns a new fresh folder with the given path under a temporary folder.
69 *
70 * @param tempFolder the temporary folder to create the folder under
71 * @return the created folder
72 * @throws IOException if an error occurs
73 */
74 public static File newFolder(final String path, final File tempFolder) throws IOException {
75 return Files.createDirectory(tempFolder.toPath().resolve(path)).toFile();
76 }
77
78 private TempDirUtils() {
79 }
80 }