[英]How to get the absolute path of a file in my project (and not of a file stored in a temporary folder)
I am using: 我在用:
I have a JSON file stored in the ./WebContent
folder. 我在./WebContent
文件夹中存储了一个JSON文件。 I am trying to get the absolute path of the JSON file in this way: 我正在尝试以这种方式获取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();
}
and the file path reconstructed from the relativePath
is: 并且从relativePath
重构的文件路径是:
/Users/kazuhira/Documents/MAC_workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/lab2_calendario/testJson.txt
Why String filePath = sc.getRealPath(relativePath);
为什么是String filePath = sc.getRealPath(relativePath);
generates a path on a temporary folder? 生成一个临时文件夹上的路径? In which way I can configure the context on the "real" json file (the same I create in the project)? 我可以通过哪种方式在“真实的” json文件上配置上下文(与在项目中创建的上下文相同)?
I suppose Tomcat is working in a temporary context, why? 我想Tomcat是在临时环境下工作的,为什么? There's a way to tell him to use the same folder of the project? 有一种方法可以告诉他使用项目的同一文件夹吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.