package com.logicbig.example.files;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
public class NewDirectoryStreamExample {
public static void main(String... args) throws IOException {
String pathString = System.getProperty("java.io.tmpdir");
Path path = Paths.get(pathString);
try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {
Iterator<Path> iterator = ds.iterator();
int c = 0;
while (iterator.hasNext() && c < 5) {
Path p = iterator.next();
System.out.println(p);
c++;
}
}
}
}
Output
C:\Users\Joe\AppData\Local\Temp\+~JF1283084198655582245.tmp
C:\Users\Joe\AppData\Local\Temp\+~JF192051292487094235.tmp
C:\Users\Joe\AppData\Local\Temp\+~JF2519104209326462184.tmp
C:\Users\Joe\AppData\Local\Temp\+~JF33147415601443728.tmp
C:\Users\Joe\AppData\Local\Temp\+~JF3396327083016795947.tmp
package com.logicbig.example.files;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class NewDirectoryStreamExample2 {
public static void main(String... args) throws IOException {
String pathString = System.getProperty("java.io.tmpdir");
Path path = Paths.get(pathString);
System.out.println("Path to stream: " + path);
//stream all files with name ending .log
try (DirectoryStream<Path> ds = Files.newDirectoryStream(path, "*.log")) {
ds.forEach(System.out::println);
}
}
}
Output
Path to stream: C:\Users\Joe\AppData\Local\Temp
C:\Users\Joe\AppData\Local\Temp\adb.log
C:\Users\Joe\AppData\Local\Temp\aria-debug-1476.log
C:\Users\Joe\AppData\Local\Temp\aria-debug-4092.log
C:\Users\Joe\AppData\Local\Temp\aria-debug-5588.log
C:\Users\Joe\AppData\Local\Temp\JavaDeployReg.log
C:\Users\Joe\AppData\Local\Temp\StructuredQuery.log
package com.logicbig.example.files;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class NewDirectoryStreamExample3 {
public static void main(String... args) throws IOException {
String pathString = System.getProperty("java.io.tmpdir");
Path path = Paths.get(pathString);
System.out.println("Path to stream: " + path);
//stream all files with name ending .log
try (DirectoryStream<Path> ds = Files.newDirectoryStream(path,
p -> p.getFileName().toString().startsWith("aria"))) {
ds.forEach(System.out::println);
}
}
}
Output
Path to stream: C:\Users\Joe\AppData\Local\Temp
C:\Users\Joe\AppData\Local\Temp\aria-debug-1476.log
C:\Users\Joe\AppData\Local\Temp\aria-debug-4092.log
C:\Users\Joe\AppData\Local\Temp\aria-debug-5588.log