首页 > 其他 > 详细

Validate File Format

时间:2014-08-08 16:13:46      阅读:326      评论:0      收藏:0      [点我收藏+]

介绍

    通过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());
		}
	}
}


Validate File Format,布布扣,bubuko.com

Validate File Format

原文:http://blog.csdn.net/three_man/article/details/38438233

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!