Java 8+ version:
import java.nio.file.Paths;
import java.nio.file.Files;
Files.createDirectories(Paths.get("/Your/Path/Here"));
The Files.createDirectories() creates a new directory and parent directories that do not exist. This method does not throw an exception if the directory already exists.
new File("/path/directory").mkdirs();
Here "directory" is the name of the directory you want to create/exist.
After ~7 year, I will update it to better approach which is suggested by Bozho.
File theDir = new File("/path/directory");
if (!theDir.exists()){
theDir.mkdirs();
}
You have to actually call some method to create the directories. Just creating a file object will not create the corresponding file or directory on the file system.
You can use File#mkdirs() method to create the directory: -
theFile.mkdirs();
Difference between File#mkdir() and File#mkdirs() is that, the later will create any intermediate directory if it does not exist.
Use this code spinet for create intermediate folders if one doesn't exist while creating/editing file:
File outFile = new File("/dir1/dir2/dir3/test.file");
outFile.getParentFile().mkdirs();
outFile.createNewFile();
I think you can use this code :
File file = new File("generatedQuestions/"+dirName+"/");
file.getParentFile().mkdirs();
PrintWriter writer = new PrintWriter(file.getAbsolutePath() +fileName+".txt");
I add file.getAbsolutePath(), because u try get file path
Try this way:
String dirName = "someDirectory";
String fileName = "file.txt";
File file = new File("generatedQuestions/" + dirName + "/" + fileName);
if(file.getParentFile().mkdirs()) {
PrintWriter printWriter = new PrintWriter(file);
}