如何在Java程序(J2EE + JSTL)中获取服务器文件夹的路径 [英] how to get the path of server's folder inside Java program (J2EE + JSTL)
问题描述
我想在基于Web的项目(J2EE-JSP + Servlets)中读取Excel文件的内容,这些项目位于Web服务器的文件夹中。
I wanted to read contents of Excel files in my web-based project (J2EE-JSP+Servlets) which are located inside the web server's folder.
我有制作了一个java文件,我将使用JSTL库通过JSP页面调用,但是我需要在Java文件中获取Excel工作表的路径,这样我才能阅读内容。
I have made a java file, which i will call through a JSP page using JSTL library, but I need to get the path of the Excel sheet in the Java file, so I can read the contents.
如何获取当前Java文件的路径以及Excel文件?
How can I get the path to the current Java file and so the Excel file?
此外,我将通过以下方式读取Excel文件的内容POI库。我能够在J2SE开发中做到这一点,但这可能吗?
Also, I will be reading the contents of the Excel file through POI library. I was able to do this in J2SE development, but is it possible here?
POIFSFileSystem fs = null;
try {
fs = new POIFSFileSystem(new FileInputStream("**some path here of sheet**"));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
HSSFWorkbook wb = null;
try {
wb = new HSSFWorkbook(fs);
} catch (IOException ex) {
ex.printStackTrace();
}
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell1,cell2,cell3;
int rows; // No of rows, stores the no. of rows for an excel sheet
int cols; // No of columns, stores the no. of columns for an excel sheet
rows = sheet.getPhysicalNumberOfRows();
cols = 5;
for(int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if(row != null) {
cell1 = row.getCell(1);
cell2 = row.getCell(2);
cell3 = row.getCell(4);
//System.out.println(cell1.getStringCellValue()+" "+cell2.getStringCellValue()+" "+cell3.getStringCellValue());
}
}
}
推荐答案
您可以要求servlet上下文相对于实际路径进行转换:
You can ask servlet context to translate relative to real path:
context.getRealPath("/");
如果java类是servlet,你可能会做类似
If you java class is servlet, you can probably do something like
getServletConfig().getServletContext();
否则,jsp页面是一个servlet,所以你可以从那里传递它。
otherwise, jsp page is a servlet, so you can pass it from there.
最后,您可以在启动应用程序时选择一次:
Finally, you can pick it up once when you start your app:
public class AppStartup implements ServletContextListener {
public void contextDestroyed(ServletContextEvent event) {
}
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
// remember it in some static class for future use
}
}
说完这一切之后,最好是创建一个具有servlet上下文,解析路径,并使用已解析的文件路径调用类的servlet,最后将请求转发到jsp页面以显示结果。
Having said all this, it's probably better to make a servlet that has his servlet context, resolve path, and call your class with resolved path to a file, then finally forward request to a jsp page to display results.
这篇关于如何在Java程序(J2EE + JSTL)中获取服务器文件夹的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!