English 中文(简体)
如何在飞行档案中搜寻/替换?
原标题:How to do a search/replace on a file on the fly?

我的java申请装上XML档案,然后用XML。

在我创建SAXBuilder之前,我想做的是搜查/替代文件。 我怎么能够记住(不必写到档案中)?

这里是我的法典,我设想进行搜查/替代:

private String xmlFile = "D:\mycomputer\extract.xml";
File myXMLFile = new File(xmlFile);

// TODO
// REPLACE ALL "<content>" in xmlFile with "<content><![CDATA["
// REPLACE ALL "</content>" with "]]></content>"

SAXBuilder builder =  new SAXBuilder("org.apache.xerces.parsers.SAXParser");

document = builder.build(new File(myXMLFile));
问题回答

Read the file into memory, do the search/replace, and use the SAXBuilder(StringReader) method.

You can first read file to string with apache commons io and then change the input source for the SaxBuilder as in the following code snippet:

String fileStr = FileUtils.readFileToString(myXMLFile);
fileStr = fileStr.replaceAll("<content>","<content><![CDATA[");
fileStr = fileStr.replaceAll("</content>","]]></content>");
SAXBuilder builder =  new SAXBuilder("org.apache.xerces.parsers.SAXParser");
document = builder.build(new ByteArrayInputStream(fileStr.getBytes()));

你回答了问题,将整个档案翻译成“斯特林堡”,代之以,然后打电话给“斯特凡”。

The string can be passed to SAXBuilder using StringReader:

StringBuilder sb = new StringBuilder ();
loadFIleContent (filePath, sb);
document = builder.build (new StringReader (sb.toString ()));

P.S.: follow up to theglauber s answer:

如果档案确实大(~100Mb),那么将它完全读到记忆中,并将其划入OM树是不切实际的。 在这种情况下,你应考虑使用SAXParser,取代档案。

根据这些档案的大小,或者读到“Sting”,你在记忆中进行更换,并从“Sting”建造“XML”,或者在读到档案时铺开新的通道,取而代之和产出,然后从“Stemo”的输出中进行XML的建设。

(我建议 par平和修改XML树或使用XML过滤器,但怀疑你想要做这种扼杀性的替换,因为你的档案内容不正确。)





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签