我想做的是读取 html 文件的内容。单击链接时,应读取 html 文件内容,并且该内容将在我的代码中的某处使用。
我尝试了什么:
我尝试将相对路径转换为绝对路径
String absoluteFilePath = servletContext.getRealPath("/html/en/TestPage.html");
这在我的 windows 开发机器上的 weblogic 中运行良好,但是当此代码部署到 Unix 上的 weblogic 时strong> machine 上面的代码返回空值。我在谷歌上搜索了一下,发现了
"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)."
能否请您建议将相对路径转换为绝对路径(使用上下文路径)的最佳方法。如果我可以从相对路径读取文件,代码应该可以在 Windows 和 Unix 平台上运行,或者以其他方式读取 html 文件,而不是从绝对路径读取。
最佳答案
如果 war 爆发,你只能使用getRealPath(...)
,但你总是可以使用 getResource( ...)
或 getResourceAsStream(...)
。在您的示例中,它将变为:
InputStream is = servletContext.getResourceAsStream("/html/en/TestPage.html");
然后你就可以安全地阅读它了......
关于java - 绝对路径的相对 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26273868/