Прослушиватель наблюдения прослушивает файлы в папке, имя которой будет другим.JAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Прослушиватель наблюдения прослушивает файлы в папке, имя которой будет другим.

Сообщение Anonymous »

У меня есть программа медицинской практики, которая позволяет пользователям вводить новых пациентов, редактировать существующих, добавлять коды диагнозов и создавать/редактировать записи на прием.
При сохранении нового пациента папка создан для хранения фотографий пациентов. Когда фотография добавляется в папку пациентов, прослушиватель просмотра выбирает фотографию и добавляет ее в список. Пока я сообщаю слушателю часов, какую папку слушать, все работает так, как задумано. Иерархия выглядит следующим образом:
dev
| GaitApp
|PatientDocuments
| Test, Patient, 1234
| Images
| Test, Patient2, 5678
| Images
| Test, Patient3, 9000
| Images

Я пытаюсь понять, как создать прослушиватель отслеживания для прослушивания каталога, в котором имя папки пациента будет другим.
Создание папка
// Specify the Directory Name
String directoryName = fName.getText() + ", " + lName.getText()+ ", " + mrn.getText();
String imagesName = "Images";

// Address of Current Directory
Path currentDirectory = Paths.get("C:\\dev\\GaitApp\\PatientDocuments");

// Specify the path of the directory to be created
String directoryPath = currentDirectory + File.separator + directoryName;
String imagesPath = directoryPath + File.separator + imagesName;

// Create a File object representing the directory
File directory = new File(directoryPath);
File imagesDirectory = new File(imagesPath);

// Attempt to create the directory
boolean directoryCreated = directory.mkdir();
boolean imagesDirectoryCreated = imagesDirectory.mkdir();

if (directoryCreated) {
System.out.println("Directory created successfully at: " + directoryCreated);
System.out.println(directoryName);
} else {
System.out.println("Failed to create directory. It may already exist at: " + directoryCreated);
}
if (imagesDirectoryCreated ) {
System.out.println("Directory created successfully at: " + imagesDirectoryCreated );
System.out.println(directoryName);
} else {
System.out.println("Failed to create directory. It may already exist at: " + imagesDirectoryCreated );
}

У меня создан прослушиватель просмотра, но он прослушивает определенную указанную папку.
прослушиватель просмотра
public ImageView imageview1;

@FXML
public ListView photoListView;

private static final Path IMAGES_FOLDER = Paths.get(
System.getProperty("user.dir"), "Images"
);

@FXML
public void initialize() throws IOException{

if (! Files.exists(IMAGES_FOLDER)) {
try {
Files.createDirectory(IMAGES_FOLDER);
System.out.println(IMAGES_FOLDER);
System.out.println(Files.createDirectory(IMAGES_FOLDER));

} catch (IOException e) {
throw new RuntimeException(e);
}
}
Thread watchFilesThread = new Thread(this::onWatchListener);
watchFilesThread.setDaemon(true);
watchFilesThread.start();

photoListView.getSelectionModel().selectedItemProperty();
photoListView.setCellFactory( p -> new ListCell() {
protected void updateItem(Image image, boolean empty) {
super.updateItem(image, empty);
if (empty || image == null) {
setText(null);
setGraphic(null);
} else {
imageview1.setImage(image);
setGraphic(imageview1);
//setText(image.getUrl());
}
}
});

}

public void onWatchListener() {
try {
WatchService watchService = FileSystems.getDefault().newWatchService();
IMAGES_FOLDER.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
boolean done = false;
while (! done) {
WatchKey key = watchService.take();
System.out.println("key");
for (WatchEvent event : key.pollEvents()) {
System.out.println("Event");
if (event.kind().type() == Path.class) {
Path path = ((WatchEvent)event).context();
Platform.runLater(() -> addImage(IMAGES_FOLDER.resolve(path)));
}
done = ! key.reset();
}
}
} catch (Exception exc) {
exc.printStackTrace();
}
}

private void addImage(Path imagePath) {
Image image = new Image(imagePath.toUri().toString());
photoListView.getItems().add(image);
photoListView.getSelectionModel().select(image);
}


Подробнее здесь: https://stackoverflow.com/questions/793 ... -different
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»