我試圖解析正在寫入的XML文件。我已經設置了一個SAX解析器來爲每個元素採取適當的操作。問題在於XML文件是以塊編寫的,並且由於緩衝(我認爲),SAX解析器並不總是讀取最新的塊並進行操作。這意味着可以有數據坐在文件中,直到進一步的數據到達纔會被處理。有沒有辦法來防止這種情況發生,以確保SAX解析器始終讀取最新的可用數據?還是有更好的方法來做這個處理?解析寫入文件時的XML文件(無緩存)
下面是我用來讀取XML文件的包裝器。我沒有看到用Java來做這件事的更好方法,儘管我願意接受建議。請注意,當我們開始閱讀時,XML文件可能不存在,所以我們可能需要等待它在此類中創建。
public class XmlFileInputStream extends InputStream {
private final File xmlFile;
private InputStream stream;
private boolean done;
private static final int POLL_INTERVAL = 100;
public XmlFileInputStream(File xmlFile) {
this.xmlFile = xmlFile;
this.stream = null;
this.done = false;
}
@Override
public int read() throws IOException {
if (!getStream()) {
return -1;
}
int c;
try {
while ((c = stream.read()) == -1 && !done) {
Thread.sleep(POLL_INTERVAL);
}
} catch (InterruptedException e) {
return -1;
}
return c;
}
private boolean getStream() throws FileNotFoundException {
if (stream == null) {
try {
while (!xmlFile.exists() && !done) {
Thread.sleep(POLL_INTERVAL);
}
} catch (InterruptedException e) {
return false;
}
try {
stream = new new FileInputStream(xmlFile);
} catch (FileNotFoundException e) {
// File deleted before we could open it
return false;
}
}
return true;
}
public void done() {
this.done = true;
}
@Override
public void close() throws IOException {
if (stream != null) {
stream.close();
}
}
}
stax有幫助嗎?它應該與流一起工作。 http://docs.oracle.com/javase/tutorial/jaxp/stax/using.html – Jayan