posts - 110, comments - 101, trackbacks - 0, articles - 7
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理
在项目中经常会遇到文件加载并解析的问题
加载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对象,然后就可以解析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 互相转换

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

上面这行报错,new InputStream 报错

下面这样写即可

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




只有注册用户登录后才能发表评论。


网站导航: