我想做的是创建一个全局FileInputStream对象,并在我的应用程序中使用它。
我有以下类,它创建我的FileInputStream objec并返回我对XML文件的查询结果:
package Engine;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
public class BACENGQueryXMLbyVTD {
public String query;
public String path;
public BACENGQueryXMLbyVTD(String query, String path) {
this.query = query;
this.path = path;
}
public ArrayList query() throws IOException, VTDException {
System.out.println(path);
File f = new File(path);
//System.out.println(f);
FileInputStream fis = new FileInputStream(f);
//System.out.println(fis);
byte[] xmlContent = new byte[(int) f.length()];
fis.read(xmlContent);
VTDGen vg = new VTDGen();
vg.setDoc(xmlContent);
vg.parse(false);
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
int node = 0;
ap.selectXPath(query);
int i;
ArrayList<String> interfaces = new ArrayList<String>();
while ((i = ap.evalXPath()) != -1) {
vn.push();
interfaces.add(vn.toString(i + 1));
}
ap.resetXPath();
return interfaces;
}
}
这个类是从我的主类调用的,它有一个循环。
for (int c = 0; c < nodeNames.size(); c++) {
String Queries2 = "/import_data/group/node[@name='" +nodeNames.get(c) + "']/interface/@network_value";
BACENGQueryXMLbyVTD getNodesInterfaces = new BACENGQueryXMLbyVTD(Queries2, TransitPath);
listOfNodeInterfaces = getNodesInterfaces.query();
}
它工作正常,但是为了减少我的服务器HD上的IO资源的消耗。我想创建一个唯一的FileInputStream对象,并将其用于必须执行的每个查询。
有人可以指出方法吗?
分离您的关注点 - BACENGQueryXMLbyVTD
既加载数据又执行查询。
首先将文件加载到循环外的byte[]
中,然后将其传递给 BACENGQueryXMLbyVTD
。 您可能还希望将query
作为参数传递给 query
方法。
您最终会得到如下所示的BACENGQueryXMLbyVTD
(免责声明我不熟悉 VTD-XML,因此从该 API 创建对象可能不会完全像这样工作):
public class BACENGQueryXMLbyVTD
{
private byte[] doc;
public BACENGQueryXMLbyVTD(byte[] doc)
{
this.doc = doc;
}
public List<String> query(String query) throws IOException, VTDException
{
VTDGen generator = new VTDGen();
generator.setDoc(doc);
generator.parse(false);
VTDNav navigator = generator.getNav();
AutoPilot autoPilot = new AutoPilot(navigator);
autoPilot.selectXPath(query);
List<String> nodeInterfaces = new ArrayList<String>();
int i;
while ((i = autoPilot.evalXPath()) != -1)
{
navigator.push();
nodeInterfaces.add(navigator.toString(i + 1));
}
return nodeInterfaces;
}
}
然后你可以这样调用:
byte[] xmlContent = ... //load the xml from anywhere you like, not just a file as previously.
BACENGQueryXMLbyVTD getNodesInterfaces = new BACENGQueryXMLbyVTD(xmlContent);
for (String nodeName : nodeNames)
{
String query = "/import_data/group/node[@name='" + nodeName + "']/interface/@network_value";
nodeInterfaces = getNodesInterfaces.query(query);
...
}
您可能还想切换到标准的Java XPATH API - 它们比VTD-XML更清晰,文档更好。