JavaFX - how to add all files from directory to TableView

大憨熊 提交于 2019-12-08 10:04:42

问题


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:


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.



来源:https://stackoverflow.com/questions/26042665/javafx-how-to-add-all-files-from-directory-to-tableview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!