Java File System - Directory

> Procedural Languages > Java > Java - IO (Input/Output) - (File System|File|Console)

1 - About

Advertising

3 - Management

3.1 - 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();
}

3.2 - 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();
        }
    }

3.3 - 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();
	}
}
Advertising

3.4 - 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

3.5 - Equality

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

3.6 - 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.