从Java创建WebContent文件夹中的文件

时间:2012-02-09 12:06:22

标签: java file webcontent

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

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

注意:不使用servlet!

编辑:

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

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

概述:

根据请求创建xml文件

要在WebContent文件夹中创建的XML文件

使用此xml文件传递数据

1 个答案:

答案 0 :(得分:-1)

Glassfish解决方案。 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);
    }
}
相关问题