JavaFX - 如何将目录中的所有文件添加到TableView [英] JavaFX - how to add all files from directory to TableView

查看:159
本文介绍了JavaFX - 如何将目录中的所有文件添加到TableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题说,所有。我想要读取文件的目录,然后写入到TableView。如何做到这一点?我想在选择目录作为数组处理文件和文件夹,然后打开并通过循环添加它们,但我不知道如何将其翻译成Java,标准库不包括有用的方法,除了打开单个文件/目录。

解决方案

如果您只想获取目录中的文件:

 的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆