Skip to content

Commit 8a5bb32

Browse files
Moving to a new module (eugenp#9681)
1 parent a074061 commit 8a5bb32

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.baeldung.emptiness;
2+
3+
import org.junit.Test;
4+
5+
import java.io.File;
6+
import java.io.IOException;
7+
import java.nio.file.DirectoryStream;
8+
import java.nio.file.Files;
9+
import java.nio.file.Path;
10+
import java.nio.file.Paths;
11+
import java.util.stream.Stream;
12+
13+
import static org.assertj.core.api.Assertions.assertThat;
14+
15+
public class DirectoryEmptinessUnitTest {
16+
17+
@Test
18+
public void givenPath_whenInvalid_thenReturnsFalse() throws IOException {
19+
assertThat(isEmpty(Paths.get("invalid-addr"))).isFalse();
20+
}
21+
22+
@Test
23+
public void givenPath_whenNotDirectory_thenReturnsFalse() throws IOException {
24+
Path aFile = Paths.get(getClass().getResource("/notDir.txt").getPath());
25+
assertThat(isEmpty(aFile)).isFalse();
26+
}
27+
28+
@Test
29+
public void givenPath_whenNotEmptyDir_thenReturnsFalse() throws IOException {
30+
Path currentDir = new File("").toPath().toAbsolutePath();
31+
assertThat(isEmpty(currentDir)).isFalse();
32+
}
33+
34+
@Test
35+
public void givenPath_whenIsEmpty_thenReturnsTrue() throws Exception {
36+
Path path = Files.createTempDirectory("baeldung-empty");
37+
assertThat(isEmpty(path)).isTrue();
38+
}
39+
40+
private static boolean isEmpty(Path path) throws IOException {
41+
if (Files.isDirectory(path)) {
42+
try (DirectoryStream<Path> directory = Files.newDirectoryStream(path)) {
43+
return !directory.iterator().hasNext();
44+
}
45+
}
46+
47+
return false;
48+
}
49+
50+
private static boolean isEmpty2(Path path) throws IOException {
51+
if (Files.isDirectory(path)) {
52+
try (Stream<Path> entries = Files.list(path)) {
53+
return !entries.findFirst().isPresent();
54+
}
55+
}
56+
57+
return false;
58+
}
59+
60+
private static boolean isEmptyInefficient(Path path) {
61+
return path.toFile().listFiles().length == 0;
62+
}
63+
}

core-java-modules/core-java-io-3/src/test/resources/notDir.txt

Whitespace-only changes.

0 commit comments

Comments
 (0)