问题
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