【问题标题】:Create and read from directories in tomcat在tomcat中创建和读取目录
【发布时间】:2011-09-16 22:19:42
【问题描述】:

我需要创建目录并在 servlet 中读取它们。

如果我想在我的webapps/appName 目录中创建一个文件夹,我应该怎么做?

目前如果我这样做:

File file = new File("conf\Conf.xml");

这将查看目录“{TOMCAT_HOME}\bin\”

如何将我的默认目录指向“{TOMCAT_HOME}\webapps\appName\”

【问题讨论】:

    标签: tomcat servlets


    【解决方案1】:

    如果我想在我的 webapps/appName 目录中创建一个文件夹,我应该怎么做才能做到这一点?

    什么都没有。您应该忘记这种方法并寻找替代方法。每当您重新部署 WAR 甚至重新启动服务器时,对 webapp 文件夹结构所做的所有更改都将不可逆转地丢失。

    您需要准备一个具有读/写权限的固定文件夹,并将其绝对磁盘文件系统路径设置为配置设置(properties/xml 文件)或 VM 参数。例如,/var/webapp/uploads。这样你就可以像往常一样使用File

    String root = getRootSomehow(); // Must return "/var/webapp/uploads".
    File file = new File(root, "somefile.txt");
    // ...
    

    一个完全不同的选择是使用数据库。如果您将 Web 应用程序部署到不允许您在 webapp 上下文之外创建文件夹的主机,这将是唯一的选择。

    【讨论】:

      【解决方案2】:

      关于为什么要这样做的问题.... 最便携的方法是将<init-param> 添加到您的 servlet 并以这种方式传递路径。

      您还可以使用System.getenv() 来获取TOMCAT_HOME 环境变量,假设它已设置。

      【讨论】:

        【解决方案3】:

        你只需要从 servlet 上下文中获取真正的路径,它会给出你正在寻找的路径,做一些这样的事情,这段代码将创建以当前日期为名称的目录。如果您想避免 servlet 启动延迟,请创建一个线程并将目录创建委托给该线程。您可以像这样将目录路径保存到 servlet 上下文。

        private static final String DIR_SERVLET_CTX_ATTRIB = "directoryPathAttrib";
        public void init() throws ServletException {
            StringBuilder filePathBuilder = new StringBuilder(getServletContext().getRealPath("/").toString());
            filePathBuilder.append(File.separator);
            filePathBuilder.append(new SimpleDateFormat("MM-dd-yyyy").format(new Date()));
            System.out.println("Directory path: "+ filePathBuilder.toString());
              File file = new File(filePathBuilder.toString());
              if(!file.exists())
              {
                  file.mkdir();
                  System.out.println("finished creating direcotry");
              }
             getServletContext().setAttribute(DIR_SERVLET_CTX_ATTRIB,  filePathBuilder.toString());
        }
        
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, java.io.IOException 
        {
            String dirPath = (String)getServletContext().getAttribute(DIR_SERVLET_CTX_ATTRIB);
            File file = new File(dirPath + File.separator + "test.txt");
            FileOutputStream fis = new FileOutputStream(file);
            fis.write("Hello".getBytes());
            fis.flush();
        }
        

        【讨论】:

        • 我做过类似的事情,因为这些文件的使用与部署相关,如果文件使用与部署无关,那么我建议不要这样做。
        猜你喜欢
        • 1970-01-01
        • 2015-03-08
        • 2021-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-29
        • 2016-02-08
        • 1970-01-01
        相关资源
        最近更新 更多