About

File System - Directory in Java

Management

Creating

// Create a path Object
Path path  = Paths.get("./myDir");
// a directory
Files.createDirectory(path);
File dir = new File("/path/To/Dir");
if (!dir.exists()) {
	dir.mkdir();
}

Delete a directory recursively

static public void deleteDirectory(File path) 
    {
        if (path == null)
            return;
        if (path.exists())
        {
            for(File f : path.listFiles())
            {
                if(f.isDirectory()) 
                {
                    deleteDirectory(f);
                    f.delete();
                }
                else
                {
                    f.delete();
                }
            }
            path.delete();
        }
    }

Looping through the child of a directory

  • With nio. newDirectoryStream opens a directory, returns a DirectoryStream to iterate over all entries in the directory. The elements returned by the directory stream's iterator are of type Path
DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dir);
int numberOfSubDir = 0;
int numberOfSubFile = 0;
for (Path path : directoryStream) {
    if (Files.isDirectory(path)){
        numberOfSubDir++;
    } else {
        numberOfSubFile++;
    }
}
File dir = new File("/path/To/Dir");
for(File f : dir.listFiles())
{
	if(f.isDirectory()) 
	{
		deleteDirectory(f);
		f.delete();
	}
	else
	{
		f.delete();
	}
}

Meta information

Path myDirectory = Paths.get("D:\\temp");
System.out.println("The directory exists ?: "+Files.exists(myDirectory));
System.out.println("The directory size in bytes is: "+Files.size(myDirectory));
System.out.println("The directory is a regular file? : "+Files.isRegularFile(myDirectory));
System.out.println("The directory is readable? : "+Files.isReadable(myDirectory));
System.out.println("The directory is executable? : "+Files.isExecutable(myDirectory));
The directory exists ?: true
The directory size in bytes is: 8192
The directory is a regular file? : false
The directory is readable? : true
The directory is executable? : true

Equality

Path myDirectory = Paths.get("D:\\temp");
System.out.println("The directory are equals? : "+Files.isSameFile(myDirectory, myDirectory));
true

Current User Directory

The current user directory is is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.