我有这样的事情:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.xml.stream.*;
import javax.xml.stream.events.*;
public class MyClass implements javax.xml.stream.StreamFilter
{
private Map myMap= new HashMap();
public Map getMap()
{
return this.myMap;
}
public void addElement(String text)
{
this.myMap.put(text, "value");
}
public void doSomething(String strValue)
{
try
{
XMLInputFactory xmlif = null;
xmlif = XMLInputFactory.newInstance();
FileInputStream fis = new FileInputStream("myFile.xml");
XMLStreamReader xmlr = xmlif.createFilteredReader(xmlif.createXMLStreamReader(fis),new MyClass());
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
OutputStream fileStream = new FileOutputStream("myFileOutput");
XMLStreamWriter xmlWriter = outputFactory.createXMLStreamWriter(fileStream);
addElement(strValue);
System.out.println(getMap().size()+"Before");
while (xmlr.hasNext())
{
write(xmlr, xmlWriter);
xmlr.next();
}
System.out.println(getMap().size()+"After");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public boolean accept(XMLStreamReader reader)
{
System.out.println(getMap().size()+"inside");
if ( getMap().containsKey("Something") )
{
System.out.println("The value is there");
}
return true;
}
private void write(XMLStreamReader xmlr, XMLStreamWriter writer) throws XMLStreamException
{
switch (xmlr.getEventType()) {
case XMLEvent.START_ELEMENT:
String localName = xmlr.getLocalName();
writer.writeStartElement(localName);
break;
}
}
}
当我将tagMap创建为静态时,它可以工作,但是由于我会将此类放在线程中,因此所有映射都将指向同一个映射,从而使比较无用。具体来说,我已经看到在函数接受内部,地图有 0 个值。
函数 accept 是接口 SteamFilter 的一部分,因此当事件发生时会自动调用它。我尝试将地图更改为公共,甚至使用构造函数设置值,但它是相同的。
在创建类的类中调用它的方式是:
Runnable runClass = new Runnable(){
public void run(){
try
{
MyClass myC = new MyClass();
myC.doSomething("value");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Thread myTask = new Thread(runClass);
myTask.start();
你知道我如何检查函数接受内的地图值吗?