Sunday 8 January 2023

Java: Check whether a directory has some files or not

Below snippet return true, if the given path is a directory and has files in it.

public static boolean hasFiles(final Path directoryPath) throws IOException {
	try (final Stream<Path> stream = Files.list(directoryPath)) {
		return stream.findAny().isPresent();
	}
}

 

Find the below working application.

 

DirectoryFilesCheck.java
package com.sample.app.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class DirectoryFilesCheck {

	/**
	 * @param directoryPath directory path
	 * @return {@code true} if the given directory path contains files
	 * @throws IOException on any I/O errors accessing the path
	 */
	public static boolean hasFiles(final Path directoryPath) throws IOException {
		try (final Stream<Path> stream = Files.list(directoryPath)) {
			return stream.findAny().isPresent();
		}
	}

	public static void main(String[] args) throws IOException {
		final String dirPath1 = "/Users/Shared";

		if (hasFiles(Paths.get(dirPath1))) {
			System.out.println("Directory '" + dirPath1 + "' has files in it");
		} else {
			System.out.println("Directory '"+ dirPath1 + "' is empty");
		}

		final Path dirPath2 = Files.createDirectories(Paths.get(dirPath1, "newDir"));
		System.out.println(dirPath2 + " is created");
		
		if (hasFiles(Paths.get(dirPath2.toString()))) {
			System.out.println("Directory '" + dirPath2 + "' has files in it");
		} else {
			System.out.println("Directory '" + dirPath2 + "' is empty");
		}
	}

}

Output

Directory '/Users/Shared' has files in it
/Users/Shared/newDir is created
Directory '/Users/Shared/newDir' is empty

 

 

You may like

file and stream programs in Java

Read file content using BufferedReader in Java

Touch the file in Java (Update the file timestamp)

Get POSIX file attributes in Java

Get file basic file attributes in Java

check whether a file is executable or not in Java

No comments:

Post a Comment