Java: single line list of dirs in a directory?

A single line list for displaying TXT files.

import java.io.File; import java.io.FilenameFilter; ... files = dir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".txt"); } } ); 

A source

Is there a single line list for the dirs list in the directory?

+4
source share
3 answers
 public static void main (String[] args) throws Exception { File dir = new File("yourDir"); FileFilter fileFilter = new FileFilter() { public boolean accept(File file) { return file.isDirectory(); } }; File[] files = dir.listFiles(fileFilter); for (File f : files) System.out.println( f.getName() ); } 
+5
source

This uses Commons IO, but it’s actually the easiest way to list all the directory names. It also has a more powerful set of filters that can be used for other purposes:

 String[] dirNames = new File("/Users/jonathan").list(DirectoryFileFilter.INSTANCE); for (String dirName: dirNames) System.out.println("Directory Name: " + dirName); 
+4
source
 import java.io.File; import java.io.FileFilter; ... files = dir.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isDirectory(); } }); 

Note the use of listFiles(FileFilter) , not listFiles(FilenameFilter) .

+3
source

Source: https://habr.com/ru/post/1305872/


All Articles