【问题标题】:How to write to a file in WebContent directory from a class in WEB-INF/classes directory如何从 WEB-INF/classes 目录中的类写入 WebContent 目录中的文件
【发布时间】:2013-05-26 14:43:36
【问题描述】:

我在动态 Web 应用程序的 WEB-INF/Classes 目录中有一个 Java 类 UpdateStats。这个类有一个函数 writeLog(),它将一些日志写入文本文件。我希望这个文本文件位于 webcontent 目录中。因此,每次调用该函数时,都会将更新统计信息写入该文本文件中。 问题是如何在该函数中给出该文本文件在 webcontent 目录中的路径,该函数位于 WEB-INF/Classes 目录中。

【问题讨论】:

  • 我希望您意识到如果您打算将数据存储的时间超过 WAR 的生命周期,那么这不是一个好的存储位置。每当您重新部署 WAR 时,部署文件夹中的任何更改都会丢失,原因很简单,这些更改不包含在 WAR 文件本身中。顺便说一句,令人失望的是,到目前为止没有一个答案考虑到这一点。

标签: java jakarta-ee tomcat file-handling web-inf


【解决方案1】:

要编写文件,您需要知道服务器上 Web 内容目录的绝对路径,因为文件类需要绝对路径。

File f = new File("/usr/local/tomcat/webapps/abc/yourlogfile.txt");
FileOutputStream out = new FileOutputStream(f);
out.writeLog("Data");

假设:abc 是你的项目名称

当您部署应用程序时,WebContent 不是任何目录。 Web 内容下的所有文件都直接在项目名称下。

【讨论】:

  • 如果我在 windows 或 mac 或其他服务器上工作怎么办?
【解决方案2】:

你可以从 ServletContext 获取你的 webapp 根目录:

String path = getServletContext().getRealPath("WEB-INF/../");
File file = new File(path);
String fullPathToYourWebappRoot = file.getCanonicalPath();

希望这会有所帮助。

【讨论】:

    【解决方案3】:

    您可以在您的 servlet 中执行以下操作,

    当您执行getServletContext().getRealPath() 并输入一些字符串参数时,该文件将在您的网络内容位置看到。 如果你想在 WEB-INF 中添加一些东西,你可以给文件名,比如“WEB-INF/my_updates.txt”。

        File update_log = null;
    final String fileName = "my_updates.txt";
    
    @Override
    public void init() throws ServletException {
        super.init();
        String file_path = getServletContext().getRealPath(fileName);
        update_log = new File(file_path);
        if (!update_log.exists()) {
            try {
                update_log.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("Error while creating file : " + fileName);
            }
        }
    }
    
    public synchronized void update_to_file(String userName,String query) {
    
        if (update_log != null && update_log.exists()) {
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(update_log, true);
                fos.write((getCurrentFormattedTime()+" "+userName+" "+query+"\n").getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多