Hello I was just wondering how to make a custom directory below the current user's home directory. I've tried this already and it doesn't work... (Code below)
I want it to go to this directory and create the folder in the documents folder
c:/users/"user"/documents/SimpleHTML/
File SimpleHTML = new File("C:/Users/"user"/Documents"); {
// if the directory does not exist, create it
if (!SimpleHTML.exists()) {
System.out.println("createing direcotry: " + SimpleHTML);
boolean result = SimpleHTML.mkdir();
if(result) {
System.out.println("Direcotry created!");
}
}
new simplehtmlEditor() {
//Calling to Open the Editor
};
}
Just add the selected path to the file you want to create. If you don't add it will use the current application path, not the one you want. File file = new File(folder, "test.
File provides methods like createNewFile() and mkdir() to create new file and directory in Java. These methods returns boolean, which is the result of that operation i.e. createNewFile() returns true if it successfully created file and mkdir() returns true if the directory is created successfully.
java File file = new File("JavaFile. java"); We then use the createNewFile() method of the File class to create new file to the specified path.
Try something like this: File file = new File("/some/absolute/path/myfile. ext"); OutputStream out = new FileOutputStream(file); // Write your data out. close();
First, use System.getProperty("user.home")
to get the "user" directory...
String path = System.getProperty("user.home") + File.separator + "Documents";
File customDir = new File(path);
Second, use File#mkdirs
instead of File#mkdir
to ensure the entire path is created, as mkdir
assumes that only the last element needs to be created
Now you can use File#exists
to check if the abstract path exists and if it doesn't File#mkdirs
to make ALL the parts of the path (ignoring those that do), for example...
if (customDir.exists() || customDir.mkdirs()) {
// Path either exists or was created
} else {
// The path could not be created for some reason
}
Updated
A simple break down of the various checks that might need to be made. The previous example only cares if the path exists OR it can be created. This breaks those checks down so that you can see what's happening...
String path = System.getProperty("user.home") + File.separator + "Documents";
path += File.separator + "Your Custom Folder"
File customDir = new File(path);
if (customDir.exists()) {
System.out.println(customDir + " already exists");
} else if (customDir.mkdirs()) {
System.out.println(customDir + " was created");
} else {
System.out.println(customDir + " was not created");
}
Note, I've added an additional folder called Your Custom Folder
to the path ;)
Note that you can use Commons-IO for this, too:
File userDirectory = org.apache.commons.io.FileUtils.getUserDirectory();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With