我有一个包含一个包和一个文件夹的项目:
%1是包。路径包:“project/src/java/basebusiness”
2是文件夹。路径文件夹:“input/run”
在文件夹中我有一个文本文件CNPM.file,在package 1中我有一个类ReadOrWriteFile。以下是ReadOrWriteFile中的代码:
public static List<String> ReadFileTXT(String pathFile) throws FileNotFoundException, IOException{
List<String> lst_result= new ArrayList<>();
String path= new File("input\\run").getAbsolutePath();
path+= pathFile;
BufferedReader bR= new BufferedReader(new FileReader(path));
String line="";
while((line= bR.readLine()) != null){
lst_result.add(line);
}
bR.close();
return lst_result;
}当我在tomcat中运行代码时,我想获取项目中文件夹的路径。
我已经编写了代码并在控制台中运行,但它不是作为web.I运行的。我使用的是tomcat 8.0.9和window。请帮帮我。
发布于 2015-03-01 18:40:26
你想要webapp的路径,比如/tomcat/webapps/mywebapp/文件夹?您需要ServletContext引用来在运行时读取路径。如果您处于JSP页面上下文中,则它是一个隐式应用程序变量。
// any servlet giving getServletContext() getter
String path = ctx.getRealPath("/");
System.out.println(path);
- - - -
// in .jsp page
String path = application.getRealPath("/"); 或者使用resourceloader接口来读取类路径,正如其中一条评论所说的那样。另一个可移植性提示是始终使用类unix路径input/run分隔符,即使在Windows box中也是如此。Java可以很好地处理它。
https://stackoverflow.com/questions/28792340
复制相似问题