“该进程无法访问该文件,因为该文件正在被另一个进程使用”

时间:2018-12-03 13:34:02

标签: java xml file

我正在编写一个程序,如果文件有效,它将移动xml;如果不是,它将被移动到“ validateXML”文件夹;如果不是,它将被移动到“ notValidateXml”。 当xml文件中没有错误但该程序运行正常时, 当方法“ validateXMLSchema”引发异常,说明文件xml无效时,progrom无法将文件移至文件夹,因此出现以下错误:

java.nio.file.FileSystemException: The process cannot access the file because it is being used by another process

使用xsd验证xml的方法:

public static boolean validateXMLSchema(String xsdPath, String xmlPath){
    Schema schema = null;
    Validator validator = null;
    try {
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schema = factory.newSchema(new File(xsdPath));
        validator = schema.newValidator();
        validator.validate(new StreamSource(new File(xmlPath)));
        return true;
    } catch (IOException | SAXException e) {

        System.out.println("Exception: "+e.toString()+"********* "+e.getLocalizedMessage());

        return false;
    }

}

方法移动文件:

 public static boolean moveFile(String sourcePath, String targetPath) {

    try {
        Path pathSource = Paths.get(sourcePath);
        Path pathTarget = Paths.get(targetPath);
        if(!Files.exists(pathTarget.getParent())){
            Files.createDirectories(pathTarget.getParent());
        }
        Files.move(pathSource,pathTarget,StandardCopyOption.ATOMIC_MOVE);
        System.out.println("File moved !!!");
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

最后是测试的主要内容

 public static void main(String[] args) throws IOException {
    boolean moved = false;

   /*  System.out.println("EmployeeRequest.xml validates against Employee.xsd? "+
             validateXMLSchema("D:\\DATA\\user\\Desktop\\employee.xsd", "D:\\DATA\\user\\Desktop\\employee.xml"));*/
     boolean b = validateXMLSchema("D:\\DATA\\user\\Desktop\\employee.xsd", "D:\\DATA\\user\\Desktop\\employee.xml");
    if(b){
         Files.newBufferedReader(Paths.get("D:\\DATA\\user\\Desktop\\employee.xml"));
        moved = moveFile("D:\\DATA\\user\\Desktop\\employee.xml","D:\\DATA\\user\\Desktop\\Files\\validateXml\\employee.xml");
    }else{
        moved = moveFile("D:\\DATA\\user\\Desktop\\employee.xml","D:\\DATA\\user\\Desktop\\Files\\notValidateXml\\employee.xml");
    }
    if(moved){
        logger.info("File moved !!!");
    }else {
        logger.warn("file cannot be moved !!!");
    }


}

0 个答案:

没有答案