我有一个包含 1 个包和 1 个文件夹的项目:
1是包。路径包:“项目/src/java/basebusiness”
2是文件夹。路径文件夹:“输入/运行”
在文件夹中我有一个文本文件 CNPM.file,在包 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 运行。我使用的是 tomcat 8.0。 9 和窗口。请帮助我。
最佳答案
你想要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("/");
或者使用资源加载器接口(interface)从类路径中读取,如评论之一所述。另一个可移植性提示始终使用类似 unix 的路径 input/run
分隔符,即使在 Windows 框中也是如此。 Java 可以很好地处理它。
关于java - 使用tomcat运行时在java中获取路径文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28792340/