Transformer transformer = tFactory.newTransformer();
Properties properties = transformer.getOutputProperties();
properties.setProperty(OutputKeys.ENCODING, "gb2312");
properties.setProperty(OutputKeys.VERSION, "1.0");
properties.setProperty(OutputKeys.INDENT, "yes");
properties.setProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperties(properties);
DOMSource source = new DOMSource(root);
java.io.File f= new java.io.File(filename + ".lock");
StreamResult result = new StreamResult(f);
transformer.transform(source, result);//输出结果到f
这时的file长时间锁定,无法rename和delete。
竟然长达22秒。对于计算机来说,22秒,都能从白垩纪发展到党的十三大召开了。
但是,在测试环境中,间隔时间小的可以忽略。
这件事情的挫败感极为强烈,小鼠感觉受到了深深的侮辱。
于是周日这一天竟然看了半天的think in java的I/O章节。
这是有生以来第一次主动学习业务知识。
书到用时方恨少啊方恨少。
虽然并没有直接的相关知识,但聊以自慰吧。
周一上午查了大量网页,并发帖求助。
无果。
不过看到有人求助,怎样用transform输出到字符串中,而不是输出到file。
于是,用了笨方法。
先从transform得sw,再写入fo中,因为fo是可以自己关闭的。
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
transformer.transform(source, result);
String s = sw.toString();
System.out.println(s);
FileOutputStream fo = null;
try
{
fo = new FileOutputStream(filename + ".lock");
fo.write(s.getBytes());
fo.close();//关闭
} catch (IOException e)
{
e.printStackTrace();
}
这时,再进行rename就很顺利了。
进行了一次调试,暂时无问题。
不过,还是不清楚所以然。
下午的时候,看到这个帖子。完全的同命人。
原来StreamResult result 可以接收fo啊!-_-!
于是改成:
java.io.FileOutputStream fo = null;
try
{
fo = new java.io.FileOutputStream(filename+".lock");
StreamResult result = new StreamResult(fo);
transformer.transform(source, result);//输出结果
fo.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
简洁些。
错误日志(1) |
关于偷懒的错误
System.out.println("--gen xml file ....."); System.out.println("--gen xml file .....");
就因为我把上面三行代码做的事情写成了一行 StreamResult result=new StreamResult(file);, 于是我始终是不能对file进行renameTo操作或者delete操作,如果开始我能发现这一点,还是值得庆幸的,但事实上我花了很长时间来找出问题,我甚至怀疑是Weblogic的限制所致,因为下面的程序在Tomcat里运行是没有问题的,但现在想来有可能是使用的TransformerFactoryImpl不同造成的,Weblogic使用的是org.apache.xalan.xsltc.trax.TransformerFactoryImpl ,而Tomcat用的是jdk默认的。后来,我尝试了很多办法来解决这个问题,最终问题指向了写入文件的输出流,我并没有显示控制文件的输出流,天知道StreamResult(file)作了什么,用java.io.FileOutputStream fos控制对文件输入,并最终关闭文件输出流,这样做了之后,再也没有什么后遗症了,ok!这种错误以后应当引以为戒。不过为什么在Tomcat中的运行完全没有问题,这其中是何道理呢?? |