Sandy
Sandy

Reputation: 14125

Relative URL to Absolute Path

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.

Upvotes: 3

Views: 782

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148880

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 ...

Upvotes: 1

Related Questions