Create a directory if it does not exist and then create the files in that directory as well
To create a directory in Java if it does not exist, you can use the java.nio.file.Files
class and its createDirectory
method. Here is an example of how you can do this:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws Exception {
String dirName = "mydir";
Path dirPath = Paths.get(dirName);
if (!Files.exists(dirPath)) {
Files.createDirectory(dirPath);
}
}
}
This code creates a Path
object representing the directory and then checks if it exists using the exists
method. If the directory does not exist, it is created using the createDirectory
method.
To create a file in the directory, you can use the java.nio.file.Files
class and its createFile
method. Here is an example of how you can do this:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws Exception {
String dirName = "mydir";
Path dirPath = Paths.get(dirName);
if (!Files.exists(dirPath)) {
Files.createDirectory(dirPath);
}
String fileName = "myfile.txt";
Path filePath = dirPath.resolve(fileName);
if (!Files.exists(filePath)) {
Files.createFile(filePath);
}
}
}
This code creates a Path
object representing the file and then checks if it exists using the exists
method. If the file does not exist, it is created using the createFile
method.
I hope this helps! Let me know if you have any other questions.