1

In Wicket I add a new image to the page:

String filename = "images/specialLogo.jpg";
add(new Image("logoImage", new ContextRelativeResource(filename)));

How can I check whether this "specialLogo.jpg" file exists, through adding before the filename a correct path where the application .war file has been placed (ContextRelative)?
In other words: how to do:

if (exists) {
  add...(specialLogo)
} else {
  add... (normalLogo)
}
Celahirius
  • 15
  • 4

2 Answers2

1

I tried this solution on my test page in Wicket project.

We can add a context to filename and that will be a full path to a file. So (as you need) if it's exists, we get it otherwise take another picture:

String context = ((WebApplication)Application.get()).getServletContext().getContextPath();
String filenameSpecial = "/images/specialLogo.jpg";
String filenameNormal = "/images/normalLogo.jpg";
File f = new File(context + filenameSpecial);
add(new Image("logoImage", new ContextRelativeResource(f.exists() ? filenameSpecial : filenameNormal)));
sanluck
  • 1,544
  • 1
  • 12
  • 22
  • Why should the poster of the question try this? Please, explain your solution. – Martin Zabel Jan 15 '16 at 22:03
  • Author said that he don't know the full path of the files so there are way to do it without it. Is there anything incorrect? I tried it on my test page. – sanluck Jan 18 '16 at 01:52
  • Your answer may be correct. But, you did **not** describe how your solution works. This would be helpful for the question author as well as further readers. _Any answer that gets the asker going in the right direction is helpful, but do try to mention any limitations, assumptions or simplifications in your answer. Brevity is acceptable, but fuller explanations are better._ - from [How do I write a good answer](http://stackoverflow.com/help/how-to-answer) – Martin Zabel Jan 18 '16 at 07:06
  • Thank you Martin I will consider you advice in future. I corrected the answer. – sanluck Jan 19 '16 at 07:53
0

One way is to use https://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getResource(java.lang.String) and check for non-null result.

Another way is https://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String) and then with the File/Path APIs

martin-g
  • 17,243
  • 2
  • 23
  • 35