挂毯5.4列表从Web应用程序文件夹中的所有图像
我的问题是,我想列出什么位于 项目/ src目录/主/ web应用/图像挂毯5.4列表从Web应用程序文件夹中的所有图像
我知道,如果我知道图像中的所有图像( s)name(s)我可以做这样的URL:
assetSource.getContextAsset(IMAGESLOCATION + imageName, currentLocale).toClientURL();
但是如果我不知道所有的图像名称?
感谢您提前给出答案!
Web应用程序(和tapestry)也不知道/关心文件的绝对路径,因为它可以在任何地方部署。 您可以通过调用HttpServletRequest的getRealPath来获得某个文件的绝对路径。 HttpServletRequest中的
@Inject
private HttpServletRequest request;
...
// get root folder of webapp
String root = request.getRealPath("/");
// get abs path from any relative path
String abs = root + '/' + relPath;
getRealPath已过时,建议使用的ServletContext.getRealPath代替,但它不是那么容易得到ServletContext的。
我更喜欢使用WebApplicationInitializer实施
public class AbstractWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// Here we store ServletContext in some global static variable
Global.servletContext = servletContext;
....
}
您基本上需要能够读取给定文件夹中的文件。下面是一些非常基本的代码,将遍历所有文件夹中:
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
}
// else, it's a directory
}
所有进口应该从java.io
package。
您好! 感谢@Dusko的回应。我写了一个类似于你的代码,但getContextAsset可以处理相对路径的主要问题,但不能绝对转换。例如当我这样做: \t \t'String path = assetSource.getContextAsset(IMAGESLOCATION + imageName,currentLocale).getResource()。getFolder(); \t \t File file = new File(path); \t \t System.out.println(Arrays.toString(file.list()));' 我得到空,但图片和文件夹存在。 – LakiGeri
谢谢!有用。 :) – LakiGeri