3

what I am trying to do is to read content of html file. On click of a link the html file content should be read and that content will be used somwhere in my code.

What I tried:

I tried converting relative path to absolute path

String absoluteFilePath = servletContext.getRealPath("/html/en/TestPage.html");

and this works fine in weblogic on my windows dev machine but when this code is deployed to webloic on Unix machine the above code is returning null. I dig up google and I found

"servletContext.getRealPath returns null if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive)."

Can you please suggest best way to convert the relative path to absolute(using context path). The code should work on windows as well as on Unix platform or some other way round to read the html file like instead of reading from absolute path if I can read file file from relative path.

Sandeep Kumar
  • 13,799
  • 21
  • 74
  • 110
  • what server are you using? can you tell us the full qualified classname of servletcontext? – Philipp Sander Oct 09 '14 at 08:45
  • 2
    seems duplicate of http://stackoverflow.com/a/12160863/2078908 – ursa Oct 09 '14 at 09:05
  • 1
    possible duplicate of [what does "/" mean in the method 'servletcontext.getRealPath'](http://stackoverflow.com/questions/12160639/what-does-mean-in-the-method-servletcontext-getrealpath) – alain.janinm Oct 09 '14 at 09:55
  • 3 upvotes for a duplicate question . cant understand what is going on – Santhosh Oct 09 '14 at 10:29
  • @SanKrish If a duplicate question describes the same issue, but in different words, that can actually be a good thing (if someone is searching while debugging their issue and happens to use this different wording, that's someone who found what they needed and might not necessarily have before). It's the "search key phrase from question and immediately get several solutions as top hits" type questions that really shouldn't get upvotes. – Dennis Meng Oct 10 '14 at 07:44
  • I'll admit though, I don't have enough context to be 100% sure which of those this question falls under. – Dennis Meng Oct 10 '14 at 07:44

1 Answers1

1

You can only use getRealPath(...) if the war is exploded, but you can always read a file under servlet context root with getResource(...) or getResourceAsStream(...). In your example, it will become :

InputStream is = servletContext.getResourceAsStream("/html/en/TestPage.html");

And then you can safely read it ...

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252