posts - 110, comments - 101, trackbacks - 0, articles - 7
            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理
          在項(xiàng)目中經(jīng)常會(huì)遇到文件加載并解析的問題
          加載Properties文件很簡單 可以直接使用Properties提供的方法就可以了

          如果是加載xml文件
          可以使用 MyTest.class.getClass().getClassLoader().getResourceAsStream(fileName);
                  try {
                       DocumentBuilder db;
                       DocumentBuilderFactory dbf 
          = DocumentBuilderFactory.newInstance();
                       dbf.setValidating(
          true);
                       dbf.setNamespaceAware(
          false);

                       db 
          = dbf.newDocumentBuilder();
                       db.setEntityResolver(
          new EntityResolver() {

                           
          public InputSource resolveEntity(String publicId, String systemId) {
                               
          if (systemId.endsWith("mapping.dtd")) {
                                   InputStream in 
          = MappingObjectInit.class.getResourceAsStream("mapping.dtd");
                                   
          if (in == null{
                                       LogLog.error(
          "Could not find [mapping.dtd]. Used [" + MappingObjectInit.class.getClassLoader() + "] class loader in the search.");
                                       
          return null;
                                   }
           else {
                                       
          return new InputSource(in);
                                   }

                               }
           else {
                                   
          return null;
                               }

                           }

                       }
          );

                       db.setErrorHandler(
          new ErrorHandler() {

                           
          public void warning(SAXParseException exception) {
                           }


                           
          public void error(SAXParseException exception) throws SAXException {
                               logger.error(exception.getMessage() 
          + " at (" + exception.getLineNumber() + ":" + exception.getColumnNumber() + ")");
                               
          throw exception;
                           }


                           
          public void fatalError(SAXParseException exception) throws SAXException {
                               logger.error(exception.getMessage() 
          + " at (" + exception.getLineNumber() + ":" + exception.getColumnNumber() + ")");
                               
          throw exception;
                           }

                       }
          );
                     
          return db; 
                  }
           catch (Exception e) {
                      logger.error(
          "", e);
                  }

          上面得到DocumentBuilder對(duì)象,然后就可以解析xml了


              private static void loadConfigurationFile(String fileName, DocumentBuilder db) {
                  Document doc 
          = null;
                  InputStream is 
          = null;
                  
          try {
                      is 
          = MappingObjectInit.class.getClass().getClassLoader().getResourceAsStream(fileName);
                      doc 
          = db.parse(is);
                  }
           catch (Exception e) {
                      
          final String s = "Caught exception while loading file " + fileName;
                      logger.error(s, e);
                      
          throw new DataAccessException(s, e);
                  }
           finally {
                      
          if (is != null{
                          
          try {
                              is.close();
                          }
           catch (IOException e) {
                              logger.error(
          "Unable to close input stream", e);
                          }

                      }

                  }

                  Element rootElement 
          = doc.getDocumentElement();
                  NodeList children 
          = rootElement.getChildNodes();
                  
          int childSize = children.getLength();

                  
          for (int i = 0; i < childSize; i++{
                      Node childNode 
          = children.item(i);

                      
          if (childNode instanceof Element) {
                          Element child 
          = (Element) childNode;

                          
          final String nodeName = child.getNodeName();
                          
          if (nodeName.equals("mapping")) {
                              String className 
          = child.getAttribute("class");
                              Class cls;
                              
          try {
                                  cls 
          = Class.forName(className);
                                  MappingMgt.reg(cls);
                              }
           catch (ClassNotFoundException e) {
                                  logger.error(
          "load configurFile from :"+fileName, e);
                              }

                              
                          }
            
                      }

                  }


                  
          if (logger.isInfoEnabled()) {
                      logger.info(
          "Loaded Engine configuration from: " + fileName);
                  }

              }

          如果使用了spring 還可以使用spring的文件加載類來加載

           <bean id="propertyConfigurer"
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
             <list>
              <value>file:${config.path}jdbc.properties</value>
              <value>file:${config.path}jms.properties</value>
             </list>
            </property>
           </bean>


          String inputstream 互相轉(zhuǎn)換

          1. String --> InputStream
          InputStream String2InputStream(String str){
             ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes());
             return stream;
          }

          2. InputStream --> String
          String inputStream2String(InputStream is){
             BufferedReader in = new BufferedReader(new InputStreamReader(is));
             StringBuffer buffer = new StringBuffer();
             String line = "";
             while ((line = in.readLine()) != null){
               buffer.append(line);
             }
             return buffer.toString();
          }


          3、File --> InputStream
          InputStream in = new InputStream(new FileInputStream(File));

          上面這行報(bào)錯(cuò),new InputStream 報(bào)錯(cuò)

          下面這樣寫即可

          new FileInputStream(file)

          4、InputStream --> File
          public void inputstreamtofile(InputStream ins,File file){
          OutputStream os = new FileOutputStream(file);
          int bytesRead = 0;
          byte[] buffer = new byte[8192];
          while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
          os.write(buffer, 0, bytesRead);
          }
          os.close();
          ins.close();
          }




          只有注冊用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 惠州市| 壤塘县| 寻甸| 鄂伦春自治旗| 平乡县| 南安市| 麦盖提县| 儋州市| 深州市| 个旧市| 葫芦岛市| 茌平县| 图木舒克市| 莱州市| 会理县| 乌苏市| 丹东市| 根河市| 泽普县| 舟曲县| 东城区| 永年县| 观塘区| 龙州县| 伊川县| 新沂市| 磐安县| 芮城县| 五家渠市| 增城市| 湘乡市| 普陀区| 吉隆县| 枞阳县| 赤水市| 赤峰市| 济阳县| 西和县| 云梦县| 康马县| 武清区|