在项目中经常会遇到文件加载并解析的问题
加载Properties文件很简单 可以直接使用Properties提供的方法就可以了
如果是加载xml文件
可以使用 MyTest.class.getClass().getClassLoader().getResourceAsStream(fileName); 

 try
        try  {
{
 DocumentBuilder db;
             DocumentBuilder db;
 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
 dbf.setValidating(true);
             dbf.setValidating(true);
 dbf.setNamespaceAware(false);
             dbf.setNamespaceAware(false);

 db = dbf.newDocumentBuilder();
             db = dbf.newDocumentBuilder();

 db.setEntityResolver(new EntityResolver()
             db.setEntityResolver(new EntityResolver()  {
{


 public InputSource resolveEntity(String publicId, String systemId)
                 public InputSource resolveEntity(String publicId, String systemId)  {
{

 if (systemId.endsWith("mapping.dtd"))
                     if (systemId.endsWith("mapping.dtd"))  {
{
 InputStream in = MappingObjectInit.class.getResourceAsStream("mapping.dtd");
                         InputStream in = MappingObjectInit.class.getResourceAsStream("mapping.dtd");

 if (in == null)
                         if (in == null)  {
{
 LogLog.error("Could not find [mapping.dtd]. Used [" + MappingObjectInit.class.getClassLoader() + "] class loader in the search.");
                             LogLog.error("Could not find [mapping.dtd]. Used [" + MappingObjectInit.class.getClassLoader() + "] class loader in the search.");
 return null;
                             return null;

 } else
                         } else  {
{
 return new InputSource(in);
                             return new InputSource(in);
 }
                         }

 } else
                     } else  {
{
 return null;
                         return null;
 }
                     }
 }
                 }
 });
             });


 db.setErrorHandler(new ErrorHandler()
             db.setErrorHandler(new ErrorHandler()  {
{


 public void warning(SAXParseException exception)
                 public void warning(SAXParseException exception)  {
{
 }
                 }


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


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

 } catch (Exception e)
        } catch (Exception e)  {
{
 logger.error("", e);
            logger.error("", e);
 }
        }上面得到DocumentBuilder对象,然后就可以解析xml了

 private static void loadConfigurationFile(String fileName, DocumentBuilder db)
    private static void loadConfigurationFile(String fileName, DocumentBuilder db)  {
{
 Document doc = null;
        Document doc = null;
 InputStream is = null;
        InputStream is = null;

 try
        try  {
{
 is = MappingObjectInit.class.getClass().getClassLoader().getResourceAsStream(fileName);
            is = MappingObjectInit.class.getClass().getClassLoader().getResourceAsStream(fileName);
 doc = db.parse(is);
            doc = db.parse(is);

 } catch (Exception e)
        } catch (Exception e)  {
{
 final String s = "Caught exception while loading file " + fileName;
            final String s = "Caught exception while loading file " + fileName;
 logger.error(s, e);
            logger.error(s, e);
 throw new DataAccessException(s, e);
            throw new DataAccessException(s, e);

 } finally
        } finally  {
{

 if (is != null)
            if (is != null)  {
{

 try
                try  {
{
 is.close();
                    is.close();

 } catch (IOException e)
                } catch (IOException e)  {
{
 logger.error("Unable to close input stream", e);
                    logger.error("Unable to close input stream", e);
 }
                }
 }
            }
 }
        }
 Element rootElement = doc.getDocumentElement();
        Element rootElement = doc.getDocumentElement();
 NodeList children = rootElement.getChildNodes();
        NodeList children = rootElement.getChildNodes();
 int childSize = children.getLength();
        int childSize = children.getLength();


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


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

 final String nodeName = child.getNodeName();
                final String nodeName = child.getNodeName();

 if (nodeName.equals("mapping"))
                if (nodeName.equals("mapping"))  {
{
 String className = child.getAttribute("class");
                    String className = child.getAttribute("class");
 Class cls;
                    Class cls;

 try
                    try  {
{
 cls = Class.forName(className);
                        cls = Class.forName(className);
 MappingMgt.reg(cls);
                        MappingMgt.reg(cls);

 } catch (ClassNotFoundException e)
                    } catch (ClassNotFoundException e)  {
{
 logger.error("load configurFile from :"+fileName, e);
                        logger.error("load configurFile from :"+fileName, e);
 }
                    }
 
                    
 }
                }  
 }
            }
 }
        }


 if (logger.isInfoEnabled())
        if (logger.isInfoEnabled())  {
{
 logger.info("Loaded Engine configuration from: " + fileName);
            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();
}