Java 中 FileWriter 写入多个文件的问题
我使用 java 和 freemarker 通过 FTL(模板文件)和 XML 生成 HTML 文件。我在多个文件中得到了结果,但每个文件都包含整个结果。我希望每个文件都包含自己的结果。为了向您提供更多详细信息,请查看我的 java 代码的这一部分:(解决方案应该很简单,但我找不到它)
static void freemarkerDo(Map datamodel, String template) throws Exception{
try {
File file = new File("Avis.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName("Avis");
Configuration cfg = new Configuration();
Template tpl = cfg.getTemplate(template);
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList flNmElmntLst = fstElmnt.getElementsByTagName("Filename");
Element flNmElmnt = (Element) flNmElmntLst.item(0);
NodeList flNm = flNmElmnt.getChildNodes();
FileWriter writer = new FileWriter(((Node) flNm.item(0)).getNodeValue()+".html");
try {
tpl.process(datamodel, writer);
}
finally{
writer.close();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
感谢您的帮助。
I'm using java with freemarker to generate HTML files through the FTL (the template file) and XML. I got the result in multiple files but each file contains the whole result. I want each file to contain its own result. To give you more details, take a look at this part of my java code: (the solution should be so easy but I can't find it)
static void freemarkerDo(Map datamodel, String template) throws Exception{
try {
File file = new File("Avis.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName("Avis");
Configuration cfg = new Configuration();
Template tpl = cfg.getTemplate(template);
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList flNmElmntLst = fstElmnt.getElementsByTagName("Filename");
Element flNmElmnt = (Element) flNmElmntLst.item(0);
NodeList flNm = flNmElmnt.getChildNodes();
FileWriter writer = new FileWriter(((Node) flNm.item(0)).getNodeValue()+".html");
try {
tpl.process(datamodel, writer);
}
finally{
writer.close();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道这个方法的作用或数据模型的设置位置,但在我看来,您正在传递整个数据模型,因此这可以解释为什么每个文件中都有整个数据模型。
调试代码时您会看到什么?
I don't know what this method does or where datamodel is set, however it would appear to me that you are passing the entire datamodel, so that would explain why you have the entire datamodel in each file.
What do you see when you debug your code?