如何从jar文件访问资源文件

时间:2015-02-19 19:40:47

标签: java maven

我已经阅读了很多类似的帖子,但我无法找到解决问题的方法:我需要验证并解析xml文件。 (针对xsd架构的验证)。问题是,在我的方法,当我运行:mvn包然后运行jar文件我得到以下错误:

java.lang.IllegalArgumentException: URI is not hierarchical
    at java.io.File.<init>(Unknown Source)
    at com.test.Main.main(Main.java:15)

这是我试过的:

后来编辑:源代码

如何在不获取流关闭异常的情况下将InputStream作为参数传递给多个方法?这是一种正确的方法吗?

public class DOMParserFile {

  private InputStream   inputXML;
  private InputStream inputXSD;
  private Set<CarPart> carParts;

  public DOMParserFile(InputStream xmlFile, InputStream xsdFile) {
    this.inputXML = xmlFile;
    this.inputXSD = xsdFile;
    carParts = new HashSet<CarPart>();
 }


 public void readFromXMLFile() throws Exception {

    if (XMLFileValidator.validateAgainstXSD(inputXML, inputXSD)) {

        DocumentBuilderFactory builderFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder builder = builderFactory
                .newDocumentBuilder();
        Document doc = builder.parse(inputXML);

        // get the carPart nodes
        NodeList carPartList = doc.getElementsByTagName("carPart");
        // store car parts into a list
        for (int i = 0; i < carPartList.getLength(); i++) {
            // build new car part object
            CarPart carPart = new CarPart();
            Node carPartNode = carPartList.item(i);
            if (carPartNode.getNodeType() == Node.ELEMENT_NODE) {
                Element elem = (Element) carPartNode;
                // set id
                carPart.setId(elem.getElementsByTagName("id").item(0)
                        .getTextContent());
                // set name
                carPart.setName(elem.getElementsByTagName("name").item(0)
                        .getTextContent());
                // set description
                carPart.setDescription(elem
                        .getElementsByTagName("description").item(0)
                        .getTextContent());
                // set quantity
                carPart.setQuantity(Integer.valueOf(elem
                        .getElementsByTagName("quantity").item(0)
                        .getTextContent()));
                // set manufacturer
                carPart.setPartManufact(elem
                        .getElementsByTagName("partManufacturer").item(0)
                        .getTextContent());
                // set price
                carPart.setPrice(Double.valueOf(elem
                        .getElementsByTagName("price").item(0)
                        .getTextContent()));
                // get the list of available vehicles
                NodeList vehicleNodeList = ((Element) carPartNode)
                        .getElementsByTagName("availableFor");
                Set<Vehicle> availableVehicles = new HashSet<Vehicle>();
                for (int j = 0; j < vehicleNodeList.getLength(); j++) {
                    Vehicle vehicle = new Vehicle();
                    Node vehicleNode = vehicleNodeList.item(j);
                    if (vehicleNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element vehicleELement = (Element) vehicleNode;
                        // set vehicle's make
                        vehicle.setMake(vehicleELement
                                .getElementsByTagName("make").item(0)
                                .getTextContent());
                        // set vehicle's model
                        vehicle.setModel(vehicleELement
                                .getElementsByTagName("model").item(0)
                                .getTextContent());
                        // get the available list of years of fabrication
                        // for
                        // this vehicle
                        NodeList yearsList = ((Element) vehicleNode)
                                .getElementsByTagName("fabricationYear");
                        Set<Integer> years = new HashSet<Integer>();
                        for (int k = 0; k < yearsList.getLength(); k++) {
                            Node yearNode = yearsList.item(k);
                            if (yearNode.getNodeType() == Node.ELEMENT_NODE) {
                                Element yearElem = (Element) yearNode;
                                years.add(Integer.valueOf(yearElem
                                        .getAttribute("yearAttr")));
                            }
                        }
                        vehicle.setFabYears(years);
                        availableVehicles.add(vehicle);
                    }

                }
                carPart.setVehicles(availableVehicles);
            }
            carParts.add(carPart);
        }
    }

}

public void printCarParts(){
    for(CarPart p :carParts){
        p.output();
    }
}

}

XMLFileValidator类

public class XMLFileValidator {


public static boolean validateAgainstXSD(InputStream xmlFile, InputStream xsdFile)
{
    try
    {
        SchemaFactory factory = 
            SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(xsdFile));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xmlFile));
        System.out.println("The XML file IS valid");
        return true;
    }
    catch(Exception ex)
    {
        System.out.println("The XML file is NOT valid");
        System.out.println("Reason: " + ex.getLocalizedMessage());
        ex.printStackTrace();
        return false;
    }
  }
}

主要课程

public class Main {

   public static void main(String args[]){  


    try {

        InputStream inXML = Main.class.getResourceAsStream("/xml/carParts.xml");
        InputStream inXSD = Main.class.getResourceAsStream("/xml/carPartsWarehouse.xsd");





        //1. dom parsing method
        System.out.println("**********************DOM PARSING METHOD************************");
        DOMParserFile dom = new DOMParserFile(inXML,inXSD);
        dom.readFromXMLFile();
        dom.printCarParts();

        //2. sax parsing method
        System.out.println("***********************SAX PARSING METHOD*************************");
        SAXParserFile sax = new SAXParserFile(inXML,inXSD);
        sax.readDataFromXml();
        sax.printCarParts();

        //3. stax parsing method
        System.out.println("***********************StAX PARSING METHOD*************************");
        StAXParserFile stax = new StAXParserFile(inXML,inXSD);
        stax.readFromXml();
        stax.printCarParts();

    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       
}

1 个答案:

答案 0 :(得分:3)

这些不是File,它们是嵌入式资源。

您可以手动打开它们,因为.jar是资源为文件的.zip个文件。但这并不是处理它们的优雅方式。

然后你可以打开Stream。所以:

InputStream s = Main.class.getResourceAsStream("/xml/carParts.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(s);
//process document