gpt4 book ai didi

java - 无法删除文件,因为该文件正在使用中

转载 作者:行者123 更新时间:2023-12-01 18:45:10 27 4
gpt4 key购买 nike

我先贴出代码,然后再详细说明:

public void createPackage(String uploadedZipLocation) throws BadException, IOException, SAXException {
String extractedFolderPath = uploadedZipLocation.split("\\.zip")[0];
File tempFolder = null;
Source xml = null;
try {
xml = new StreamSource(extractedFolderPath + "/web.xml");
validatePkgXml(xml, extractedFolderPath + "/web.xml");
xml = null;
} catch (IOException e) {
throw e;
} catch (BadException bpe) {
xml = null;
tempFolder = new File(extractedFolderPath);
FileUtils.deleteDirectory(tempFolder); // **** Can't delete the folder because it is in use. web.xml is still being read in validatePkgXml I think
throw bpe;
}
}


private void validatePkgXml(Source xmlStream, String xmlPath) throws BadException, IOException, SAXException{
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new File("/C:/workspacesFresh2/web.xsd"));
Validator validator = schema.newValidator();
validator.setErrorHandler(new PackageXMLValidationErrorHandler());
try {
validator.validate(xmlStream);
logger.info(xmlStream.getSystemId() + " is valid");
} catch (SAXException e) {
logger.error(xmlStream.getSystemId() + " is NOT valid");
throw new BadException(xmlPath, e.getLocalizedMessage());
}
}

我正在尝试获取 xml 文件并根据 xsd 架构验证它。如果验证失败,我想删除包含xml文件的文件夹。当验证失败时,我无法删除该文件夹,因为 web.xml 仍在使用中。我尝试在验证失败后将 Source 设置为 null,但 web.xml 不知何故仍在使用中。有什么想法如何解锁该文件以便我可以删除它吗?附注:如果验证成功,则删除文件夹也成功。

最佳答案

删除文件夹之前需要关闭InputStream。

我还没有测试过这段代码,但它应该能给你一个想法:

public void createPackage(String uploadedZipLocation) throws BadException, IOException, SAXException {
String extractedFolderPath = uploadedZipLocation.split("\\.zip")[0];
File tempFolder = null;
StreamSource xml = null;
FileInputStream file = null;

try {
file = new FileInputStream(extractedFolderPath + "/web.xml");
xml = new StreamSource(file);
validatePkgXml(xml, extractedFolderPath + "/web.xml");
xml.getInputStream().close();
//xml = null;
} catch (IOException e) {
xml.getInputStream().close();
throw e;
} catch (BadException bpe) {
//xml = null;
xml.getInputStream().close();
tempFolder = new File(extractedFolderPath);
FileUtils.deleteDirectory(tempFolder); // **** Can't delete the folder because it is in use. web.xml is still being read in validatePkgXml I think
throw bpe;
}
}

希望它有效!祝你好运!

[编辑]顺便提一句。您应该始终关闭文件和流以避免内存泄漏,从而导致 OutOfMemoryExceptions 和 ConcurrentModificationExceptions。[/编辑]

关于java - 无法删除文件,因为该文件正在使用中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18084584/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com