JavaFX - how to add all files from directory to TableView


Question

Title says all. I want to directory of files to be read and then write to TableView. How to do this? I thought about treating files and folders in choosen directory as array and then open and add them one by on through loop but I don't know how to translate this into java, standard libraries doesn't include helpfull methods except opening single file/directory.

1
0
9/25/2014 3:42:01 PM

If you just want to get the files in a directory:

TableView<File> table = new TableView<>();
// configure table columns etc
File dir = ... ;
table.getItems().addAll(dir.listFiles());

If you want to recursively go through sub-directories (to a given depth), use the java.nio API:

TableView<Path> table = new TableView<>();
// configure table columns etc

File fileDir = directoryChooser.showDialog(mainStage);
if (fileDir != null) { // if the user chose something:
    Path dir = fileDir.toPath() ;
    int depth = ... ; // maximum depth to search, use Integer.MAX_VALUE to search everything
    Files.find(dir, depth, (path, attributes) -> 
        path.getFileName().toString().toLowerCase().endsWith(".mp3")) // select only mp3 files
        .forEach(table.getItems()::add);
}

In the last (long) statement, Files.find(...) produces a (Java 8) Stream<Path>. The code invokes forEach(...) on that stream, to add each element to the items in a table view.

1
9/26/2014 7:17:22 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon