【发布时间】:2020-05-23 21:20:39
【问题描述】:
我正在使用 StAX 将新的 Record 对象添加到名为“archive.xml”的 XML 文件中。一般的方法是:
- 检查文件是否存在,如果不存在 - 新建一个;
-
创建 XMLEventReader 和 XMLEventWriter;
3.1 如果文件是根据列表的第一项创建的,只需使用 writer 将记录添加到“archive.xml”;
3.2。如果文件存在,则从“archive.xml”中读取所有内容并将其并行写入“temp.xml”,最后添加新记录。用“temp.xml”重写“archive.xml”。
但是第 3.2 项的最后阶段会抛出错误java.nio.file.FileSystemException: The process cannot access the file because it is being used by another process (in sun.nio.fs.WindowsException)。
可能是什么问题?
public boolean create(Record record) {
String fileName="archive.xml"
boolean flag = false;
File file = new File(fileName);
if (!file.exists()) {
try {
file.createNewFile();
flag = true;
} catch (IOException ioe) {
System.err.println("Can't create new file");
return false;
}
}
//Create StAX reader and writer
XMLEventReader reader=null;
XMLEventWriter writer=null;
try {
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
if (flag) {//if writing to new file
writer = xmlOutputFactory.createXMLEventWriter(new FileOutputStream(file));
/*using writer here*/
writer.close();
} else {//if adding to existing file
File temp=new File("temp.xml");
writer = xmlOutputFactory.createXMLEventWriter(new FileOutputStream(temp));
reader = xmlInputFactory.createXMLEventReader(new FileInputStream(file));
while (reader.hasNext()) {
/*reading from "archive.xml", writing to "temp.xml"
in the end - adding new Record to "temp.xml"*/
}
reader.close();
writer.close();
//trying to rewrite "archive.xml" with "temp.xml" (but cannot get access to file)
try {
Files.move(Path.of(temp.toURI()),Path.of(file.toURI()),StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException fileNotFoundException) {
System.err.println("File not found");
} catch (XMLStreamException xmlStreamException) {
xmlStreamException.printStackTrace();
}finally {
try {
if(reader!=null)
reader.close();
if(writer!=null)
writer.close();
} catch (XMLStreamException e) {
e.printStackTrace();
}
}
return false;
}
【问题讨论】:
-
您应该确保遵循堆栈跟踪。行号将是你的线索.. 似乎你可以。正在创建文件两次。