gpt4 book ai didi

java - 如何获取我的 war 文件的某些文件夹中的文件列表?

转载 作者:行者123 更新时间:2023-11-30 08:29:05 25 4
gpt4 key购买 nike

我有一个 Java 项目(Spring)。我需要从文件夹“图像”中获取图像列表并随机选择其中一个。我在从我的 war 文件中的这个目录获取文件列表时遇到问题。我可以使用什么类(class)?以及如何设置文件夹路径?感谢您的帮助!

附言我使用的服务(不是 Controller)应该从我的图像文件夹中给我一个随机图像的名称?看起来像:

<body style="background: url(request.getContextPath() + RandomBackgroundService.getRandomBackground()) ...

我的服务会是什么样子?

最佳答案

您可以从ServletContext.getResourcePaths() 获取列表- 只需将引用自动连接到您的 Controller 并请求正确的文件夹 -

@Controller
@RequestMapping("/whatever")
public class MyClass {

@Autowired
private final ServletContext context;

@RequestMapping(method = RequestMethod.GET)
public String get(ModelMap model) {
Random rand = new Random();
List<String> images = new ArrayList<String>(context.getResourcePaths("/images"));
model.addAttribute("randomImage", images.get(rand.nextInt(images.size())));
return "myPage";
}

}

关于java - 如何获取我的 war 文件的某些文件夹中的文件列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19734133/

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