我正在使用:
我有一个存储在./WebContent
文件夹中的JSON文件。我试图以这种方式获取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);
在临时文件夹上生成路径?我可以通过哪种方式在" real"上配置上下文。 json文件(我在项目中创建的相同)?
我认为Tomcat正在临时工作中,为什么?有办法告诉他使用项目的同一个文件夹吗?