分享

系统路径问题

 posondlq 2012-05-25

 1.如何获得当前文件路径常用:

(1).Test.class.getResource("")得到的是当前类FileTest.class文件的URI目录。不包括自己!

(2).Test.class.getResource("/")得到的是当前的classpath的绝对URI路径。

(3).Thread.currentThread().getContextClassLoader().getResource("")得到的也是当前ClassPath的绝对URI路径。

(4).Test.class.getClassLoader().getResource("")得到的也是当前ClassPath的绝对URI路径。

(5).ClassLoader.getSystemResource("")得到的也是当前ClassPath的绝对URI路径。尽量不要使用相对于System.getProperty("user.dir")当前用户目录的相对路径,后面可以看出得出结果五花八门。

(6) new File("").getAbsolutePath()也可用。

2.Web服务器

(1).Tomcat在类中输出System.getProperty("user.dir");显示的是%Tomcat_Home%/bin

(2).Resin不是你的JSP放的相对路径,是JSP引擎执行这个JSP编译成SERVLET的路径为根.比如用新建文件法测试File f = new File("a.htm");这个a.htm在resin的安装目录下

(3).如何读文件使用ServletContext.getResourceAsStream()就可以

(4).获得文件真实路径String? file_real_path=ServletContext.getRealPath("mypath/filename"); ?不建议使用request.getRealPath("/");

3.文件操作的类,不建议使用,可以使用commons io类

此处省略三千行代码。

4.遗留问题目前new FileInputStream()只会使用绝对路径,相对没用过,因为要相对于web服务器地址,比较麻烦还不如写个配置文件来的快哪5.按Java文件类型分类读取配置文件配置文件是应用系统中不可缺少的,可以增加程序的灵活性。

java.util.Properties是从jdk1.2就有的类,一直到现在都支持load ()方法,jdk1.4以后save(output,string) ->store(output,string)。如果只是单纯的读,根本不存在烦恼的问题。

web层可以通过 Thread.currentThread().getContextClassLoader().getResourceAsStream("xx.properties") 获取;

Application可以通过new FileInputStream("xx.properties");直接在classes一级获取。

关键是有时我们需要通过web修改配置文件,我们不能将路径写死了。经过测试觉得有以下心得:

1.servlet中读写。

如果运用Struts 或者Servlet可以直接在初始化参数中配置,调用时根据servletcontext的getRealPath("/")获取真实路径,再根据String file = this.servlet.getInitParameter("abc");获取相对的WEB-INF的相对路径。

例:

  1. InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("abc.properties");  
  2. Properties prop = new Properties();  
  3. prop.load(input);  
  4. input.close();  
  5. OutputStream out = new FileOutputStream(path);  
  6. prop.setProperty("abc", “test");  
  7. prop.store(out, “CtestC");  
  8. out.close();  

 

2.直接在jsp中操作,通过jsp内置对象获取可操作的绝对地址。

例:// jsp页面

  1. String path = pageContext.getServletContext().getRealPath("/");  
  2. String realPath = path+"/WEB-INF/classes/abc.properties";//java 程序   
  3. InputStream in = getClass().getClassLoader().getResourceAsStream("abc.properties");   
  4.   
  5. // abc.properties放在webroot/WEB-INF/classes/ 目录下   
  6. prop.load(in);  
  7. in.close();  
  8. OutputStream out = new FileOutputStream(path); // path为通过页面传入的路径   
  9. prop.setProperty("abc", “abcccccc");  
  10. prop.store(out, “CtestC");  
  11. out.close();  


3.只通过Java程序操作资源文件

  1. InputStream in = new FileInputStream("abc.properties"); // 放在classes同级   
  2. OutputStream out = new FileOutputStream("abc.properties");  


 

 

 

>>1.web环境下得到系统路径

  1. /** 
  2.      * 删除指定目录下指定格式的文件 
  3.      * 由于生成报表的过程中会生成很多bmp格式的图片,现在设定每次刷新的时候把这些图片都删除掉 
  4.      */  
  5.     public void deleteFileInPath(HttpServletRequest request, HttpServletResponse response) {  
  6.         ServletContext sc = request.getSession().getServletContext();  
  7.         String rootpath = sc.getRealPath(""); //值为D:\apache-tomcat-6.0.26\webapps\webmonitor   
  8.         File myPath = new File(rootpath);  
  9.         if (myPath.isDirectory()) {  
  10.             String strSubs[] = myPath.list();  
  11.             for (int i = 0; i < strSubs.length; i++) {  
  12.                 //判断文件类型,当文件类型为指定的类型时才执行删除操作   
  13.                 String type = strSubs[i].substring(strSubs[i].indexOf(".")+1);  
  14.                 //要用绝对路径才能删除掉   
  15.                 File file = new File(rootpath + "\\" + strSubs[i]);  
  16.                 if (file.isFile() && type.equals("bmp")) {  
  17.                     file.delete();  
  18.                 }  
  19.             }  
  20.         }  
  21.     }  


 >>2.非web环境下得到系统路径:

  1. package com.glnpu.birt;  
  2.   
  3. import java.io.InputStream;  
  4. import java.io.IOException;  
  5. import java.util.Properties;  
  6. import java.util.logging.Level;  
  7.   
  8. import javax.servlet.ServletContext;  
  9.   
  10. import org.eclipse.birt.report.engine.api.EngineConfig;  
  11. import org.eclipse.birt.report.engine.api.IReportEngine;  
  12. import org.eclipse.birt.core.framework.PlatformServletContext;  
  13. import org.eclipse.birt.core.framework.IPlatformContext;  
  14. import org.eclipse.birt.core.framework.Platform;  
  15. import org.eclipse.birt.core.exception.BirtException;  
  16. import org.eclipse.birt.report.engine.api.IReportEngineFactory;  
  17.   
  18. /** 
  19.  * 报表引擎 
  20.  * 用来初始化Report Engine 
  21.  * @author dashan.yin 
  22.  * 
  23.  */  
  24. public class BirtEngine {  
  25.   
  26.     private static IReportEngine birtEngine = null;  
  27.     private static Properties configProps = new Properties();  
  28.     private final static String configFile = "com/glnpu/birt/BirtConfig.properties";  
  29.       
  30.     public static synchronized void initBirtConfig() {  
  31.         loadEngineProps();  
  32.     }  
  33.       
  34.     /** 
  35.      * 报表引擎是ReportEngine类的一个实例,是任何报表应用程序的关键部分。 
  36.      * 首先用EngineConfig对象来为ReportEngine准备参数,然后用BIRT报表引擎工厂来创建引擎。 
  37.      * 创建一个配置对象:  
  38.      * EngineConfig config = new EngineConfig();  
  39.      * @param sc 
  40.      * @return 
  41.      */  
  42.     public static synchronized IReportEngine getBirtEngine(ServletContext sc) {  
  43.         if (birtEngine == null) {  
  44.             EngineConfig config = new EngineConfig();  
  45.             if (configProps != null) {  
  46.                 String logLevel = configProps.getProperty("logLevel");  
  47.                 Level level = Level.OFF;  
  48.                 if ("SEVERE".equalsIgnoreCase(logLevel)) {  
  49.                     level = Level.SEVERE;  
  50.                 } else if ("WARNING".equalsIgnoreCase(logLevel)) {  
  51.                     level = Level.WARNING;  
  52.                 } else if ("INFO".equalsIgnoreCase(logLevel)) {  
  53.                     level = Level.INFO;  
  54.                 } else if ("CONFIG".equalsIgnoreCase(logLevel)) {  
  55.                     level = Level.CONFIG;  
  56.                 } else if ("FINE".equalsIgnoreCase(logLevel)) {  
  57.                     level = Level.FINE;  
  58.                 } else if ("FINER".equalsIgnoreCase(logLevel)) {  
  59.                     level = Level.FINER;  
  60.                 } else if ("FINEST".equalsIgnoreCase(logLevel)) {  
  61.                     level = Level.FINEST;  
  62.                 } else if ("OFF".equalsIgnoreCase(logLevel)) {  
  63.                     level = Level.OFF;  
  64.                 }  
  65.                   
  66.                 /** 
  67.                  * 使用日志环境调试应用程序  
  68.                  * BIRT报表引擎使用java.util.logging的Logger和Level类来处理引擎平台的日志信息。 
  69.                  * 你在Eclipse中运行一个 应用程序运行信息默认的是显示在控制台上的。 
  70.                  * 在非Eclipse环境中运行信息的输出就要有运行环境决定了。 
  71.                  * 默认的日志级别是Level.INFO,你可 以通过改变日志级别来减少系统内部的日志信息。  
  72.                  * 使用EngineConfig.setLogConfig( )可以让日志输出到磁盘文件中。 
  73.                  * 该方法需要两个参数,第一个参数是日志输出的目录,BIRT 引擎会在指定目录中创建一个名称格式为ReportEngine_YYYY_MM_DD_hh_mm_ss.log的日志文件。 
  74.                  * 第二个参数是日志信息的最低级别,级别越高输出的日志信息越少。 
  75.                  * ReportEngine.changeLogLevel( )方法可以让你修改日志级别。 
  76.                  * 使用BIRT日志的例子: 
  77.                  * config.setLogConfig( "C:/Temp", Level.ERROR );    
  78.                  * engine.changeLogLevel( Level.INFO );  
  79.                  */  
  80.                 config.setLogConfig(configProps.getProperty("logDirectory"),level);  
  81.             }  
  82.             /** 
  83.              * BIRT home就是BIRT plug-ins和类库的路径,它是报表引擎的关键参数。  
  84.              * 你可以用下面的方式进行BIRT home设置:  
  85.              * 对于独立的应用程序可以通过下面的方式设置:  
  86.              * config.setBIRTHome ( "C:/birt-runtime-<version>/ReportEngine" );  
  87.              * 也可以在你自己的环境变量中设置:  
  88.              * set BIRT_HOME="C:\birt-runtime-<version>\ReportEngine"  
  89.              * SET CLASSPATH=%BIRT_HOME%\<required library 1>;  
  90.              * 在Web应用程序里要首先取得绝对路径然后设置到config  
  91.              * config.setBIRTHome( servletContext.getRealPath( "/WEB-INF" ) );  
  92.              * 在WAR 文件的Web应用程序中可以使用PlatformServletContext.  
  93.              * config.setBIRTHome( "" );  
  94.              * 在Eclipse中,通过VM运行参数设置  
  95.              * -DBIRT_HOME="C:\birt-runtime-<version>\ReportEngine"  
  96.              */  
  97.             //注意下面是setEngineHome   
  98.             config.setEngineHome("");  
  99.               
  100.             /** 
  101.              * 设置上下文  
  102.              * BIRT是一个基于Eclipse的应用程序,因此它使用OSGI平台来启动插件来产生报表和设计引擎。 
  103.              * BIRT需要的plug-in存储在 BIRT主目录下,通过platform context进行配置, 
  104.              * 它实现了接口org.eclipse.birt.core.framework.IPlatformContext。 
  105.              * context作为EngineConfig的一个参数通过setEngineContext( )进行设置 。 
  106.              * 对于web应用上部署的BIRT应用程序,使用PlatformServletContext。 
  107.              * 它使用基于资源连接的J2EE ServletContext来定位BIRT plug-in。 
  108.              * 它默认使用“/WEB-INF/platform/”  
  109.              * IPlatformContext context = new PlatformServletContext(request.getSession().getServletContext());  
  110.              * config.setPlatformContext(context);  
  111.              * 如果默认的BIRT提供的实现不能满足你的要求,可以定义自己的实现。  
  112.              *  
  113.              */  
  114.             IPlatformContext context = new PlatformServletContext(sc);  
  115.             config.setPlatformContext(context);  
  116.             try {  
  117.                 /** 
  118.                  * 启动平台 
  119.                  * 设置完成平台上下文环境,你可以通过org.eclipse.birt.core.framework.Platform类启动一个平台。 
  120.                  * Platform是一个Eclipse OSGI平台的包装类,提供一个同步的静态方法startup( )用来启动平台,该操作的开销比较大,因此你的应用程序最好只调用一次。 
  121.                  * 平台使用结束后调用Platform.shutdown( )关闭。 
  122.                  * 如果你是在Web应用程序里使用报表引擎,请在servlet的init方法中调用startup方法或者在第一次处理用到平台的请求时。最好启 动平台的代码封装为一个单例。 
  123.                  * 如果你使用Birt提供的Web Viewer或使用基于Eclipse的富客户端程序(RCP),你就不需要启动平台,因为应用程序已经自己启动了OSGi。  
  124.                  */  
  125.                 Platform.startup(config);  
  126.             } catch (BirtException e) {  
  127.                 e.printStackTrace();  
  128.             }  
  129.               
  130.             /** 
  131.              * 创建报表引擎  
  132.              * BIRT提供一个工厂服务用于创建ReportEngine对象。 
  133.              * Platform.createFactoryObject( )创建一个实现了org.eclipse.birt.report.engine.api.IReportEngineFactory接口的工厂对象。 
  134.              * 该 方法需要一个PlatformConfig对象。 
  135.              * 因为EngineConfig是继承自PlatformConfig,你可以使用 EngineConfig来创建一个工厂。 
  136.              * 最后通过IReportEngineFactory.createReportEngine( )方法和刚才使用的EngineConfig对象创建报表引擎。 
  137.              */  
  138.             IReportEngineFactory factory = (IReportEngineFactory) Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);  
  139.             birtEngine = factory.createReportEngine(config);  
  140.   
  141.         }  
  142.         return birtEngine;  
  143.     }  
  144.   
  145.     public static synchronized void destroyBirtEngine() {  
  146.         if (birtEngine == null) {  
  147.             return;  
  148.         }  
  149.         birtEngine.shutdown();  
  150.         Platform.shutdown();  
  151.         birtEngine = null;  
  152.     }  
  153.   
  154.     public Object clone() throws CloneNotSupportedException {  
  155.         throw new CloneNotSupportedException();  
  156.     }  
  157.   
  158.     /** 
  159.      * 把需要的类库都引入classpath或开发工具中。 
  160.      * 配置BIRT目录,目录中包含了从报表设计文件生成报表所需要的plug-in和类库。 
  161.      * BIRT的报表引擎包在他的ReportEngine子目录里提供了完整的BIRT home。 
  162.      * 如果你想动手修改BIRT源码的话,一定要保证源码的版本与BIRT home中的plug-in和类库的版本是一致的。  
  163.      *  
  164.      * 类库和plug-in: 
  165.      * BIRT home的ReportEngine\lib子目录和ReportEngine\plugins中包含了报表应用程序需要的用到的类库和plug-in, 
  166.      * 你可以根据自己项目的情况删除掉不用的包。  
  167.      *  
  168.      * jdbc驱动: 
  169.      * BIRT home的plugins/org.eclipse.birt.report.data.oda.jdbc_...文件夹用于存放连接数据库所需要的驱动程序, 
  170.      * 你可以把需要的驱动程序包放到该目录下(引入classpath中好像是不起作用的…) 
  171.      */  
  172.     private static void loadEngineProps() {  
  173.         try {  
  174.             /** 
  175.              * 得到当前的classpath的绝对路径的URI表示法: 
  176.              * Thread.currentThread().getContextClassLoader().getResource("")来得到当前的classpath的绝对路径的URI表示法。 
  177.              * 1.servlet中读写。如果运用Struts 或者Servlet可以直接在初始化参数中配置,调用时根据servlet的getRealPath("/")获取真实路径,再根据String file = this.servlet.getInitParameter("abc");获取相对的WEB-INF的相对路径。 
  178.              * 例:InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("abc.properties"); 
  179.              * Properties prop = new Properties(); 
  180.              * prop.load(input);</span> <span style="font-size: medium; "><br> 
  181.              * input.close(); 
  182.              *  
  183.              * prop.setProperty("abc", “test"); 
  184.              * prop.store(new FileOutputStream(path), “–test–"); 
  185.              * out.close(); 
  186.              *  
  187.              * 2.直接在jsp中操作,通过jsp内置对象获取可操作的绝对地址。 
  188.              *  // jsp页面 
  189.              *  String path = pageContext.getServletContext().getRealPath("/"); 
  190.              *  String realPath = path+"/WEB-INF/classes/abc.properties"; 
  191.                  
  192.              *  //java 程序 
  193.              *  InputStream in = getClass().getClassLoader().getResourceAsStream("abc.properties"); // abc.properties放在webroot/WEB-INF/classes/目录下 
  194.              *  prop.load(in); 
  195.              *  in.close(); 
  196.                  
  197.              *  OutputStream out = new FileOutputStream(path); // path为通过页面传入的路径 
  198.              *  prop.setProperty("abc", “abcccccc"); 
  199.              *  prop.store(out, “–test–"); 
  200.              *  out.close(); 
  201.                  
  202.              *  3.只通过Java程序操作资源文件 
  203.              *  InputStream in = new FileInputStream("abc.properties"); // 相对路径,项目下的路径 
  204.              *  OutputStream out = new FileOutputStream("abc.properties"); 
  205.              *  
  206.              */  
  207.             // Config File must be in classpath   
  208.             ClassLoader cl = Thread.currentThread().getContextClassLoader();  
  209.             InputStream in = null;  
  210.             in = cl.getResourceAsStream(configFile);  
  211.             configProps.load(in);  
  212.             in.close();  
  213.         } catch (IOException e) {  
  214.             e.printStackTrace();  
  215.         }  
  216.     }  
  217. }  

项目排列如图所示:

 

第二个试题非web环境下获得系统路径:

  1. package com.autonavi.parsexml;  
  2.   
  3. import javax.xml.parsers.DocumentBuilderFactory;  
  4. import javax.xml.parsers.DocumentBuilder;  
  5. import org.w3c.dom.Document;  
  6. import org.w3c.dom.Element;  
  7. import org.w3c.dom.NamedNodeMap;  
  8. import org.w3c.dom.Node;  
  9. import org.w3c.dom.NodeList;  
  10.   
  11. public class XmlParser {  
  12.   
  13.     // 去处理一个关于学生的信息的xml文件   
  14.     public static void main(String[] args) {  
  15.         // TODO Auto-generated method stub   
  16.         try {  
  17.   
  18.             // 解析器工厂类,为创建一个解析器作准备)   
  19.             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
  20.             // 创建一个dom解析器   
  21.             // 他实现了解析和处理xml文件需要的全部dom方法   
  22.             DocumentBuilder db = dbf.newDocumentBuilder();  
  23.               
  24.             System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));  
  25.             String url = Thread.currentThread().getContextClassLoader().getResource("").toString();  
  26.               
  27.             System.out.println("url: " + url);  
  28.               
  29.             // 告诉解析器去解析哪个xml文件   
  30.             Document dm = db.parse(url + "config/mjy.xml");  
  31.   
  32.             // 如果把整个xml看作一个公司,那么NodeList就好像是一个部门   
  33.             NodeList nl = dm.getElementsByTagName("state");  
  34.   
  35.             System.out.println("the length=" + nl.getLength());  
  36.   
  37.             for (int i = 0; i < nl.getLength(); i++) {  
  38.   
  39.                 // element就像是部门中的一个职员   
  40.                 Element ele = (Element) nl.item(i);  
  41.   
  42.                 // 也可以遍历得到所有属性和它们的值   
  43.                 // 就像该职员的相关属性   
  44.                 NamedNodeMap nnm = ele.getAttributes();  
  45.   
  46.                 for (int j = 0; j < nnm.getLength(); j++) {  
  47.                     Node node3 = nnm.item(j);  
  48.                     System.out.println("名称为:" + node3.getNodeName());  
  49.                     System.out.println("值为:" + node3.getNodeValue());  
  50.   
  51.                 }  
  52.             }  
  53.   
  54.         } catch (Exception e) {  
  55.             // TODO: handle exception   
  56.             e.printStackTrace();  
  57.         }  
  58.   
  59.     }  
  60.   
  61. }  


项目排列:


 

 

主要是下面这几句代码:

  1. String url = Thread.currentThread().getContextClassLoader().getResource("").toString();  
  2. // 告诉解析器去解析哪个xml文件   
  3. Document dm = db.parse(url + "config/mjy.xml");  


 

  1. Thread.currentThread().getContextClassLoader().getResource("");  

上面这句代码表示:当前ClassPath的绝对URI路径

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多