java - 如何获取项目中文件的绝对路径(而不是存储在临时文件夹中的文件)

标签 java json eclipse tomcat servlets

我正在使用:

  • 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 是在一个临时上下文中工作,为什么?有办法告诉他使用项目的同一个文件夹吗?

最佳答案

是的,您可以通过更改 Eclipse 中服务器配置中的一个选项

enter image description here

在单选按钮列表中选择第二个选项:)

关于java - 如何获取项目中文件的绝对路径(而不是存储在临时文件夹中的文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36452585/

相关文章:

java - 将变量放入 Java 模式中

java - 使用 CXF 和 wsdl2java 生成代码时解决冲突

java - Hibernate:我需要 flush() 吗?

json - Rswag 模式不会因数组中对象的无效属性而失败

javascript - 使用 javascript 和 Ajax POST 形成 JSON [LARAVEL]

java - 在 IntelliJ 中浏览自动完成选项时查看完整的 javadoc

java - 使用 native SQL 的 Hibernate 批处理

java - 更新 SQLite 数据库

php - 通过 HTML 将复杂变量传递给 javascript 的正确方法

eclipse - 如何配置 Eclipse 格式化程序在字段声明之间不插入空行?