gpt4 book ai didi

java - 列出 spring-boot 中目录的文件

转载 作者:行者123 更新时间:2023-12-01 17:18:10 31 4
gpt4 key购买 nike

是否有一种简单的方法来显示我的 SPRING BOOT (v 2.1) resources/static 文件夹的目录列表?

这些文件位于 resources/static 下,我可以单独访问它们,但我想要列出所有文件,并通过单击如图所示的标题来打开它们。

我想“公开”resources/static/logs 下的日志文件。如果可能的话,用 Kotlin 回答问题。

我在 SO 上发现了类似的问题,但没有帮助: Spring boot Tomcat – Enable/disable directory listing

Directory Listing

最佳答案

试试这个。它检测新文件和文件夹(注册新文件夹观察程序)并执行一些逻辑。

配置类中的某处...

@Bean(name = "storageWatchService")
public WatchService createWatchService() throws IOException {
return FileSystems.getDefault().newWatchService();
}

@Component
public class StorageWatcher implements ApplicationRunner {

private static final Logger LOG = LoggerFactory.getLogger(StorageWatcher.class);

private static final WatchEvent.Kind<Path>[] WATCH_EVENTS_KINDS = new WatchEvent.Kind[] {StandardWatchEventKinds.ENTRY_CREATE};

private static final Map<WatchKey, Path> KEY_PATH_MAP = new HashMap<>();

@Resource
private PPAFacade ppaFacade;

@Resource
private WatchService storageWatchService;

@Resource
private Environment environment;

@Override
public void run(ApplicationArguments args) {
try {
registerDir(Paths.get(environment.getProperty(RINEX_FOLDER)), storageWatchService);

while (true) {
final WatchKey key = storageWatchService.take();
for (WatchEvent<?> event : key.pollEvents()) {
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE && event.context() instanceof Path) {
final String fullPath = KEY_PATH_MAP.get(key) + "\\" + event.context().toString();
final File file = new File(fullPath);

if (file.isDirectory()) {
registerDir(file.toPath(), storageWatchService);
} else {
ppaFacade.process(file);
}
}
}
if (!key.reset()) {
KEY_PATH_MAP.remove(key);
}
if (KEY_PATH_MAP.isEmpty()) {
break;
}
}
} catch (InterruptedException e) {
LOG.error("StorageWatcher has been interrupted. No new files will be detected and processed.");
}
}

private static void registerDir(Path path, WatchService watchService) {

if (!Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) {
return;
}
try {
LOG.info("registering: " + path);
final WatchKey key = path.register(watchService, WATCH_EVENTS_KINDS);
KEY_PATH_MAP.putIfAbsent(key, path);
Arrays.stream(path.toFile().listFiles()).forEach(f -> registerDir(f.toPath(), watchService));
} catch (IOException e) {
LOG.error(MessageFormat.format("Can not register file watcher for {0}", path), e);
}
}
}

关于java - 列出 spring-boot 中目录的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61346086/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com