我正在使用:
- Eclipse Java EE IDE for Web Developers 版本:Mars.2 Release (4.5.2);
- Apache Tomcat v8.0;
- 一个网络动态项目;
- Java Servlet。
我有一个 JSON 文件存储在 ./WebContent
文件夹中。我试图通过这种方式获取 JSON 文件的绝对路径:
ServletContext sc = request.getSession().getServletContext();
//String absolutePath = "/Users/kazuhira/Documents/MAC_workspace/lab2_calendario/WebContent/Database/Events.json";
String relativePath = "eventsBackup.json";
String filePath = sc.getRealPath(relativePath);
System.out.println("(saverServlet): the path of the file is "+filePath);
//System.out.println("(saverServlet): the path of the file is "+absolutePath);
//File file = new File(absolutePath);
String content = request.getParameter("jsonEventsArray");
try (FileOutputStream fop = new FileOutputStream(file)) {
System.out.println("(saverServlet): trying to access to the file"+filePath);
// if file doesn't exists, then create it
if (!file.exists()) {
System.out.println("(saverServlet): the file doesn't exists");
file.createNewFile();
System.out.println("(saverServlet): file "+filePath+" created");
}
System.out.println("(saverServlet): writing on the file "+filePath);
// get the content in bytes
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("(saverServlet): events backup done");
} catch (IOException e) {
e.printStackTrace();
}
根据relativePath
重构的文件路径为:
/Users/kazuhira/Documents/MAC_workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/lab2_calendario/testJson.txt
为什么 String filePath = sc.getRealPath(relativePath);
在临时文件夹上生成路径?我可以通过哪种方式在“真实”json 文件(我在项目中创建的文件)上配置上下文?
我想 Tomcat 是在一个临时上下文中工作,为什么?有办法告诉他使用项目的同一个文件夹吗?
最佳答案
关于java - 如何获取项目中文件的绝对路径(而不是存储在临时文件夹中的文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36452585/