答案 0 :(得分:0)
您可以通过执行以下操作从目录中获取所有文件:
File myfolder = new File("path/to/directory");
File[] allFiles = folder.listFiles();
for (int i = 0; i < all.length; i++) {
if (allFiles[i].isFile()) {
System.out.println("File " + allFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + allFiles[i].getName());
}
}
但是,不是将其打印到输出,而是可以使用文件添加标签。
也许这样的事情就是你想要的:
File myfolder = new File("your/path");
File[] allFiles = folder.listFiles();
VBox yourBox = new VBox();
for (int i = 0; i < all.length; i++) {
if (allFiles[i].isFile()) {
yourBox.getChildren().add(new Label(allFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
//Do whatever you want to do with subfolders.
}
}
编辑:要在运行时选择文件夹,您可以使用:
DirectoryChooser https://docs.oracle.com/javase/8/javafx/api/javafx/stage/DirectoryChooser.html 或FileChooser,允许选择多个文件。
编辑完整代码(已测试):
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class test extends Application {
@Override
public void start(final Stage stage) {
stage.setTitle("File Chooser");
final FileChooser fileChooser = new FileChooser();
final Button openMultipleButton = new Button("Open Files...");
VBox yourBox = new VBox();
openMultipleButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(final ActionEvent e) {
List<File> list = fileChooser.showOpenMultipleDialog(stage);
if (list != null) {
for (File file : list) {
yourBox.getChildren().add(new Label(file.getName()));
}
}
}
});
HBox all = new HBox();
all.getChildren().addAll(openMultipleButton, yourBox);
final Pane rootGroup = new VBox(12);
rootGroup.getChildren().addAll(all);
rootGroup.setPrefSize(400, 400);
stage.setScene(new Scene(rootGroup));
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
希望这有帮助, 斯特芬