JavaFX - 如何将目录中的所有文件添加到TableView [英] JavaFX - how to add all files from directory to TableView
问题描述
如果您只想获取目录中的文件:
的TableView<文件> table = new TableView<>();
//配置表格列等
文件dir = ...;
table.getItems()。addAll(dir.listFiles());
如果你想递归遍历子目录(到给定的深度),使用java。 nio API:
TableView< Path> table = new TableView<>();
//配置表格列等
文件fileDir = directoryChooser.showDialog(mainStage);
if(fileDir!= null){//如果用户选择了一些东西:
Path dir = fileDir.toPath();
int depth = ...; //最大深度搜索,使用Integer.MAX_VALUE搜索所有内容
Files.find(dir,depth,(path,attributes) - >
path.getFileName()。toString()。toLowerCase ).endsWith(。mp3))//只选择mp3文件
.forEach(table.getItems():: add);
$ b $最后(长)语句文件。 find(...)
产生一个(Java 8) Stream< Path>
。该代码在该流上调用 forEach(...)
,将每个元素添加到表视图中的 items
。
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.
解决方案 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.
这篇关于JavaFX - 如何将目录中的所有文件添加到TableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!