我的Java路上那些事兒

          快樂(lè)成長(zhǎng)
          posts - 110, comments - 101, trackbacks - 0, articles - 7
            BlogJava :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理
          在項(xiàng)目中經(jīng)常會(huì)遇到文件加載并解析的問(wèn)題
          加載Properties文件很簡(jiǎn)單 可以直接使用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的文件加載類來(lái)加載

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




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


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 荣昌县| 乌拉特前旗| 瑞金市| 长葛市| 剑阁县| 奉贤区| 钟山县| 望谟县| 喀喇| 济宁市| 壤塘县| 平湖市| 南溪县| 黄大仙区| 喀喇| 丽江市| 麦盖提县| 团风县| 青浦区| 吉水县| 丹东市| 新乐市| 科技| 昆明市| 龙海市| 泸溪县| 盐山县| 西畴县| 九江县| 博湖县| 衡山县| 冀州市| 安福县| 景洪市| 永嘉县| 铜川市| 长垣县| 凤庆县| 格尔木市| 平阳县| 休宁县|