【问题标题】:Create A File in the WebContent Folder From Java在 Java 的 WebContent 文件夹中创建一个文件
【发布时间】:2012-02-09 12:06:22
【问题描述】:

我想知道如何使用 Java 在动态 Web 项目的 WebContent 文件夹中创建文件?

剩下的基本问题是如何获取 WebContent 文件夹的路径。

注意:不能使用 servlet!

编辑:

好的,我正在尝试从 java 方法创建一个新的 xml 文件。我希望在 WebContent 文件夹中创建该文件,以便即使在部署应用程序时也会创建该文件。

我正在使用 Jboss、maven、JSF 来创建动态 Web 项目。我需要 xml 文件将数据传递给 highcharts。请注意,我将只使用这种方法。

概览:

根据要求创建 xml 文件

在 WebContent 文件夹本身中创建的 XML 文件

使用这个xml文件来传递数据

【问题讨论】:

  • 你能详细说明你的问题吗?
  • 这不是一个好主意,尤其是因为许多较新的应用服务器正在使用虚拟文件系统来部署您的 Web 内容。
  • 在不违反 servlet 规范的情况下,您不能这样做,这会使您的 Web 应用程序依赖于供应商特定的副作用。
  • @HemantMetalia 请检查编辑
  • 没有。使用谷歌。读取文件并将读取的内容写入流需要 15 行基本 IO。我不会为你做这项工作。 Google for Java IO 教程。

标签: java file webcontent


【解决方案1】:

玻璃鱼溶液。 AbstractSearchPageBean - 你的任何班级

private static final String WEB_INF = "WEB-INF";

public static String getWebPath() {
    final String webInfPath = getWebInfPath();
    return webInfPath.substring(0, webInfPath.indexOf(WEB_INF) - 1);
}

public static String getWebInfPath() {
    String filePath = "";

    java.net.URL url = AbstractSearchPageBean.class.getResource("AbstractSearchPageBean.class");
    if (url != null) {
        String className = url.getFile();
        filePath = (className.contains(WEB_INF)) ? className.substring(0, className.indexOf(WEB_INF) + WEB_INF.length()) : className;
    }
    return filePath.replace("%20", " ");
}

// Create file in webapp/xml directory
private void createXmlFile(String xml) {
    try {
        String fileName = System.currentTimeMillis() + ".xml";
        File file = new File(Settings.getWebPath() + File.separatorChar + "xml" + File.separatorChar + fileName);
        logger.debug("parseXML(): Creating file: " + file.getAbsolutePath());
        if (file.createNewFile()) {
            FileWriter fw = new FileWriter(file);
            fw.write(this.parseXML(xml));
            fw.flush();
            fw.close();
            logger.debug("parseXML(): file saved to the: " + Settings.getAPPLICATION_DOMAIN() + '/' + fileName);
        } else {
            logger.warn("parseXML(): Can't create file: " + file.getAbsolutePath());
        }
    } catch (IOException ioe) {
        logger.error("parseXML(): Bad save file: ", ioe);
    }
}

【讨论】:

  • 谢谢,但我正在使用 Jboss AS 7
猜你喜欢
  • 1970-01-01
  • 2020-10-19
  • 2019-05-02
  • 2017-01-27
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多