How would I go about determining whether a file or directory has been created in Java?
I basically want to create a data directory if one is not already present.
Thanks.
You can call File#exists() to determine if it exists, but you can also just call File#mkdirs() to automatically create the whole path if not exist.
I usually use this technique:
File folderLocation = new File("/blah/blah/mysystem/myfolder");
if (folderLocation.exists()) {
if (!folderLocation .isDirectory()) {
throw new IOException("File-system item with path [" + folderLocation.getAbsolutePath() + "] exists but is not a folder.");
}
} else {
if (!folderLocation.mkdirs()) {
throw new IOException("Could not create folder with path : " + folderLocation.getAbsolutePath());
}
}
// we are guaranteed that the folder exists here
Related
How do I create Directory/folder?
Once I have tested System.getProperty("user.home");
I have to create a directory (directory name "new folder" ) if and only if new folder does not exist.
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();
}
With Java 7, you can use Files.createDirectories().
For instance:
Files.createDirectories(Paths.get("/path/to/directory"));
You can try FileUtils#forceMkdir
FileUtils.forceMkdir("/path/directory");
This library have a lot of useful functions.
mkdir vs mkdirs
If you want to create a single directory use mkdir
new File("/path/directory").mkdir();
If you want to create a hierarchy of folder structure use mkdirs
new File("/path/directory").mkdirs();
Create a single directory.
new File("C:\\Directory1").mkdir();
Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.
new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()
Source: this perfect tutorial , you find also an example of use.
For java 7 and up:
Path path = Paths.get("/your/path/string");
Files.createDirectories(path);
It seems unnecessary to check for existence of the dir or file before creating, from createDirectories javadocs:
Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists.
The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
If this method fails, then it may do so after creating some, but not all, of the parent directories.
The following method should do what you want, just make sure you are checking the return value of mkdir() / mkdirs()
private void createUserDir(final String dirName) throws IOException {
final File homeDir = new File(System.getProperty("user.home"));
final File dir = new File(homeDir, dirName);
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Unable to create " + dir.getAbsolutePath();
}
}
Neat and clean:
import java.io.File;
public class RevCreateDirectory {
public void revCreateDirectory() {
//To create single directory/folder
File file = new File("D:\\Directory1");
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
//To create multiple directories/folders
File files = new File("D:\\Directory2\\Sub2\\Sub-Sub2");
if (!files.exists()) {
if (files.mkdirs()) {
System.out.println("Multiple directories are created!");
} else {
System.out.println("Failed to create multiple directories!");
}
}
}
}
Though this question has been answered. I would like to put something extra, i.e.
if there is a file exist with the directory name that you are trying to create than it should prompt an error. For future visitors.
public static void makeDir()
{
File directory = new File(" dirname ");
if (directory.exists() && directory.isFile())
{
System.out.println("The dir with name could not be" +
" created as it is a normal file");
}
else
{
try
{
if (!directory.exists())
{
directory.mkdir();
}
String username = System.getProperty("user.name");
String filename = " path/" + username + ".txt"; //extension if you need one
}
catch (IOException e)
{
System.out.println("prompt for error");
}
}
}
Just wanted to point out to everyone calling File.mkdir() or File.mkdirs() to be careful the File object is a directory and not a file. For example if you call mkdirs() for the path /dir1/dir2/file.txt, it will create a folder with the name file.txt which is probably not what you wanted. If you are creating a new file and also want to automatically create parent folders you can do something like this:
File file = new File(filePath);
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
This the way work for me do one single directory or more or them:
need to import java.io.File;
/*enter the code below to add a diectory dir1 or check if exist dir1, if does not, so create it and same with dir2 and dir3 */
File filed = new File("C:\\dir1");
if(!filed.exists()){ if(filed.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filel = new File("C:\\dir1\\dir2");
if(!filel.exists()){ if(filel.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filet = new File("C:\\dir1\\dir2\\dir3");
if(!filet.exists()){ if(filet.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
if you want to be sure its created then this:
final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
final boolean logsDirExists = logsDir.exists();
assertThat(logsDirExists).isTrue();
}
beacuse mkDir() returns a boolean, and findbugs will cry for it if you dont use the variable. Also its not nice...
mkDir() returns only true if mkDir() creates it.
If the dir exists, it returns false, so to verify the dir you created, only call exists() if mkDir() return false.
assertThat() will checks the result and fails if exists() returns false. ofc you can use other things to handle the uncreated directory.
This function allows you to create a directory on the user home directory.
private static void createDirectory(final String directoryName) {
final File homeDirectory = new File(System.getProperty("user.home"));
final File newDirectory = new File(homeDirectory, directoryName);
if(!newDirectory.exists()) {
boolean result = newDirectory.mkdir();
if(result) {
System.out.println("The directory is created !");
}
} else {
System.out.println("The directory already exist");
}
}
Here is one attractiveness of the java, using Short Circuit OR '||', testing of the directory's existence along with making the directory for you
public File checkAndMakeTheDirectory() {
File theDirectory = new File("/path/directory");
if (theDirectory.exists() || theDirectory.mkdirs())
System.out.println("The folder has been created or has been already there");
return theDirectory;
}
if the first part of the if is true it does not run the second part and if the first part is false it runs the second part as well
public class Test1 {
public static void main(String[] args)
{
String path = System.getProperty("user.home");
File dir=new File(path+"/new folder");
if(dir.exists()){
System.out.println("A folder with name 'new folder' is already exist in the path "+path);
}else{
dir.mkdir();
}
}
}
I am trying to create a folder call "YouDown" at the moment I don't care where the folder is located but at this time all I want to figure out is creating it. I found that my first issue was that mkdir() and mkdirs() were being ignored due to not knowing it was a Boolean value. I created the Boolean of success and now its not being ignored. Following this I created log.d of each step in detecting to creating to already existing. It registers that it "Doesn't exist" , "Being Created" then either "Created" or "Creation Failed". It jumps to the "Creation Failed". Everything I find now to help is just being repetitive to what I've been reading for the past few days. I am also looking into how I could apply this to a specific path way like the variable string I want it to be created inside the directories Music folder
// Lastest try
String Tag2 = "YouDown"
if (!dir.exists()) {
Log.d(Tag2,"Doesnt Exist");
boolean success = false;
try{
success = dir.mkdir();
Log.d(Tag2,"Being Created");
}
catch(SecurityException se){
//handle it
}
if(success) {
Log.d(Tag2, "Created");
} else{
Log.d(Tag2, "Creation Failed");
}
}
// Other Try
String path = "/sdcard/Music/Youdown"
if(new File(path).exists()){
Log.d(Tag2, "Exists");
} else {
Log.d(Tag2, "Being Created");
Boolean succes = new File(path).mkdir();
if(success){
Log.d(Tag2, "Created"
} else {
Log.d(Tag2, "Failed"
}
Newest attempt
File dir = new File(Environment.getExternalStorageDirectory(), path2);
Boolean A = dir.mkdirs();
if(A){
Log.d(Tag2,"Created");
}
if(!A){
Log.d(Tag2,"Failed");
}
Although Android has a hierarchical file system your app may read and write in certain places only. As a start I suggest using the method getDir() of android.content.Context. As the doc states:
Retrieve, creating if needed, a new directory in which the application can place its own custom data files. You can use the returned File object to create and access files in this directory. Note that files created through a File object will only be accessible by your own application; you can only set the mode of the entire directory, not of individual files.
If you want to access shared directories you need to call other methods, for example Context.getExternalFilesDir().
If you are creating the directory for your app only, such that if ever your app gets deleted the folder gets deleted too, you can use getFilesDir().
File internalDir = getContext().getFilesDir();
String path = "/Music/Youdown";
// to create it you can call, new File(internalDir, path).mkdir();
Or alternatively if you want the external storage you would use the Environment.getExternalStorage(); like below:
String path = "/Music/Youdown";
File f = new File(Environment.getExternalStorageDirectory(), path );
if (!f.exists()) {
f.mkdirs();
}
I'm trying to create an empty .properties file on my filesystem using java.io.File.
My code is:
File newFile = new File(new File(".").getAbsolutePath() + "folder\\" + newFileName.getText() + ".properties");
if (newFile.createNewFile()){
//do sth...
}
It says that it's impossible to find the specified path.
Printing the Files's constructor's argument it shows correctly the absolute path.
What's wrong?
You can use new File("folder", newFileName.getText() + ".properties") which will create a file reference to the specified file in the folder directory relative to the current working directory
You should make sure that the directory exists before calling createNewFile, as it won't do this for you
For example...
File newFile = new File("folder", newFileName.getText() + ".properties");
File parentFile = newFile.getParentFile();
if (parentFile.exists() || parentFile.mkdirs()) {
if (!newFile.exists()) {
if (newFile.createNewFile()){
//do sth...
} else {
throw new IOException("Could not create " + newFile + ", you may not have write permissions or the file is opened by another process");
}
}
} else {
throw new IOException("Could not create directory " + parentFile + ", you may not have write permissions");
}
I think the "." operator might be causing the error not sure what you are trying to do there, may have misunderstood your intentions but try this instead:
File newFile = new File(new File("folder\\").getAbsolutePath() + ".properties");
Trivially I missed that new File(".").getAbsolutePath() returns the project's absolute path with the . at the end so my folder whould be called as .folder. Next time I'll check twice.
I have following pieces of code:
if (e.getSource() == theView.addButton) {
System.out.println("Add Button clicked");
theView.setBotTextArea("Adding category...");
File directory = new File(theModel.getDirectory() + theView.getCategoryNameInput());
boolean isDirectoryCreated = directory.mkdir();
if(isDirectoryCreated) {
System.out.println("Created new directory in: " + directory);
} else if (directory.exists()) {
System.out.println("Category already exists!");
}
}
This is part of the ActionListener's ActionPerformed() method.
private File directory = new File("C:/Users/Lotix/Desktop/TestFolder/");
public File getDirectory() {
return directory;
}
What i expect this method to do is to create a subfolder in the chosen directory. However, for some reason unknown to me, it creates completly another folder on my desktop instead of TestFolder.
I tried theModel.getDirectory().toString() and manipulating the variable but to no avail. The solution i came up with is to simply add forward slash between
theModel.getDirectory() and theView.getCategoryNameInput() such as this:
File directory = new File(theModel.getDirectory() + "/" + theView.getCategoryNameInput());
However, when i concatenate File variable with another String it works perfectly fine.
What gives?
Any file you create in your own Desktop directory appears on your desktop. That's what the folder is for.
This doesnt have anything to do with 'interaction with String and File', or Java.
Hello there I want to create the directories and sub directories with the java.
My directory structure is starts from the current application directory, Means in current projects directory which looks like following...
Images
|
|+ Background
|
|+ Foreground
|
|+Necklace
|+Earrings
|+Etc...
I know how to create directory but I need to create sub directory I tried with following code what should be next steps ?
File file = new File("Images");
file.mkdir();
You can use File.mkdir() or File.mkdirs() to create a directory. Between the two, the latter method is more tolerant and will create all intermediate directories as needed. Also, since I see that you use "\\" in your question, I would suggest using File.separator for a portable path separator string.
Starting from Java 7, you can use the java.nio.file.Files & java.nio.file.Paths classes.
Path path = Paths.get("C:\\Images\\Background\\..\\Foreground\\Necklace\\..\\Earrings\\..\\Etc");
try {
Files.createDirectories(path);
} catch (IOException e) {
System.err.println("Cannot create directories - " + e);
}
This is a tricky solution (because I used only one path to go to the whole structure).
If you don't like tricky solutions, you can use 4 simple paths instead:
Path p1 = Paths.get("C:\\Images\\Background");
Path p2 = Paths.get("C:\\Images\\Foreground\\Necklace");
Path p3 = Paths.get("C:\\Images\\Foreground\\Earrings");
Path p4 = Paths.get("C:\\Images\\Foreground\\Etc");
and then call the createDirectories method for all of them:
Files.createDirectories(p1);
Files.createDirectories(p2);
Files.createDirectories(p3);
Files.createDirectories(p4);
You can create all parent directories by using File.mkdirs().
File.mkdirs() - Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
You could do it with File#mkdirs() and something like,
// The "/" is cross-platform safe as a path-separator in Java.
// So is "\\" but that's twice the characters!
String path = createImages.getAbsolutePath() + "/Images";
File f = new File(path);
if (!f.isDirectory()) {
boolean success = f.mkdirs();
if (success) {
System.out.println("Created path: " + f.getPath());
} else {
System.out.println("Could not create path: " + f.getPath());
}
} else {
System.out.println("Path exists: " + f.getPath());
}
Per the linked Javadoc,
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
You can just use file.mkdirs(), it will create sub-directory.
String path = images + File.separator + Background + File.separator + Foreground + File.separator + Necklace + File.separator + Earrings ;
File file = new File( path );
file.mkdirs();
Adding up to #ROMANIA_engineer's answer..
I used Path.resolve() method to create sub-directories using variables lika DateTime and others:
private final Path root = Paths.get("target\\");
private final Path batchFilePath = Paths.get(root.resolve(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyymmdd_HHmmss"))).toString());
Files.createDirectory(root);
Files.createDirectory(batchFilePath);
And the result was:
directory/subdirectory example