简体   繁体   English

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

[英]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: 我在用:

  • Eclipse Java EE IDE for Web Developers version: Mars.2 Release (4.5.2); 用于Web开发人员的Eclipse Java EE IDE版本:Mars.2发行版(4.5.2);
  • Apache Tomcat v8.0; Apache Tomcat v8.0;
  • a Web Dynamic project; Web动态项目;
  • a Java Servlet. Java Servlet。

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? 有一种方法可以告诉他使用项目的同一文件夹吗?

Yes, you can by changing an option in your Server configuration in Eclipse 是的,您可以通过在Eclipse中更改服务器配置中的一个选项

在此处输入图片说明

Select the second option in the radio button list :) 在单选按钮列表中选择第二个选项:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM