首页 > 代码库 > Validate File Format
Validate File Format
介绍
通过Schema来校验File格式的正确与否。
package shuai.study.validator; import java.io.File; import java.io.IOException; import java.net.URL; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.xml.sax.SAXException; public class FormatValidator { public static boolean isFormatValid(URL urlSchema, Source source) { boolean validatorFlag = true; SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); try { Schema schema = schemaFactory.newSchema(urlSchema); Validator validator = schema.newValidator(); validator.validate(source); } catch (SAXException se) { validatorFlag = false; se.printStackTrace(); } catch (IOException ioe) { validatorFlag = false; ioe.printStackTrace(); } return validatorFlag; } public static void main(String[] args) { URL urlSchema = FormatValidator.class.getResource("/schema/TestFileFormat.xsd"); String sourceFileString = FormatValidator.class.getResource("/xml/TestSourceFile.xml").getPath(); Source source = new StreamSource(new File(sourceFileString)); boolean validatorFlag = FormatValidator.isFormatValid(urlSchema, source); if (validatorFlag) { System.out.println("Analyze " + source.getSystemId() + " successfully"); } else { System.out.println("Fail to analyze " + source.getSystemId()); } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。