Created
July 19, 2012 18:29
-
-
Save sanaulla123/3145846 to your computer and use it in GitHub Desktop.
Listing and filtering directory content
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 DirectoryFilterTest { | |
public static void main(String[] args) { | |
Path basePath = Paths.get("D:/tests"); | |
// Listing the files in the directory | |
System.out.println("All files:"); | |
try (DirectoryStream<Path> pathList = Files.newDirectoryStream(basePath)) { | |
for (Path path : pathList) { | |
System.out.println(path.toString()); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
// Applying filter using GLOB pattern | |
System.out.println("All text files[Using Glob pattern]:"); | |
try (DirectoryStream<Path> pathList = Files.newDirectoryStream(basePath, | |
"*.txt")) { | |
for (Path path : pathList) { | |
System.out.println(path.toString()); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
// Using DirectoryStream.Filter class | |
System.out.println("All document files[Using Filter class]"); | |
DirectoryStream.Filter<Path> documentFilter = new DirectoryStream.Filter<Path>() { | |
@Override | |
public boolean accept(Path entry) throws IOException { | |
String fileName = entry.getFileName().toString(); | |
return fileName != null && fileName.endsWith("txt"); | |
} | |
}; | |
try (DirectoryStream<Path> pathList = Files.newDirectoryStream(basePath, | |
documentFilter)) { | |
for (Path path : pathList) { | |
System.out.println(path.toString()); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment