zoukankan      html  css  js  c++  java
  • 在javaweb中通过servlet类和普通类读取资源文件

    javaweb有两种方式读取资源文件

    在Servlet中读取,可以使用servletContextservletContext可以拿到web所有的资源文件,然后随便读,但是这种方法不常用,尽量少在Servlet中读取资源文件

    在普通Java类中(DAO中),使用类加载器来读  和 绝对路径来读取

          类装载器可以访问的范围是classes文件夹下的文件

     

    src文件夹下面的文件在发布之后都会在classes文件夹下,也就是整个类加载器,都可以通过类加载器来操作

    1. 使用servletContext

    软件开发中,用作资源文件(配置文件)的文件类型有两种:xml文件和properties文件 

    比如新建一个properties文件,用作数据库的配置

    url=jdbc:mysql://localhost:3006/test
    username=test
    password=123

    然后在Servlet中读取文件

    public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    InputStream instream
    = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.propertites"); Properties pro = new Properties(); //map pro.load(instream); String url = pro.getProperty("url"); String username = pro.getProperty("username"); System.out.println(url); System.out.println(username); }

    其中路径不能写成"/src/db.propertites", / 表示当前web程序

    因为最终读取的是发布在服务器中的文件。都是在classes文件夹下面

    对于properties文件的操作都可以使用properties这个类

    这个类是把文件中的数据以map形式存储,

    有几行就会有几个元素

    注意:

    我们在写Java的时候常用下面这种方式读取文件,但是在javaweb中是不行的

    public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
    
          FileInputStream  instream = new FileInputStream("/WEB-INF/classes/db.propertites");    
          Properties pro = new Properties(); //map
          pro.load(instream);
          
          String url = pro.getProperty("url");
          String username = pro.getProperty("username");
            
          System.out.println(url);
          System.out.println(username);
        }
      FileInputStream  instream = new FileInputStream("/WEB-INF/classes/db.propertites");    

    考虑清楚这个相对路径是相对谁的。

    这句话是由服务器来调用,服务器由Java虚拟机来运行,所以这个是相对Java虚拟机的启动目录

    Java虚拟机的目录是?

    我们启动服务器都是在C: omcatin目录下的startup.bat,启动的时候同时启动虚拟机

    所以是相对的是这个目录。。

    所以,在javaweb中读取文件,用Servlet不能使用这种方式,这种方式必须把文件放在Java虚拟机目录下

    传统方式也不是不可行,必须要知道文件的绝对路径 

    使用servletContext先得到文件在磁盘的绝对路径。

    public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
          String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.propertites")
          FileInputStream  instream = new FileInputStream(path);    
          Properties pro = new Properties(); //map
          pro.load(instream);
          
          String url = pro.getProperty("url");
          String username = pro.getProperty("username");
            
          System.out.println(url);
          System.out.println(username);
        }

    这中方式可以得到该文件的名称。

    因为有时间文件名称是客户机传过来的,开发者需要知道

    就需要截取path字符串了。

    path.substring(path.lastIndexOf("\") +1)

     2. 使用类装载器

    对数据库配置文件的读取,一般是不放在servlet中的,一般是放在DAO类中

    这样才能把web层和数据层分开来

    类装载器:

      Java虚拟机使用每一个类的第一件事情就是将该类的字节码装载近来,装载类字节码的功能是由类装载器完成的,类装载器负责根据一个类的名称来定位和生成类的字节码数据后返回给Java虚拟机。最常见的类装载器是将要加载的类名转换成一个.class文件名,然后从文件系统中找到该文件并读取其中的内容,这种类装载器也不是直接将.class文件中的内容原封不动地返回给Java虚拟机,它需要将.class文件中的内容转换成Java虚拟机使用的类字节码。不管类装载器采用什么方式,只要能够在内存中制造出给Java虚拟机调用类字节码即可,所以把类装载器描述为类字节码的制造器更容易让人理解。 

        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            userDAO dao= new userDAO();
            dao.update();
            
          
        }
    public class userDAO {
    
        public void update() throws IOException {
            
          InputStream instream =userDAO.class.getClassLoader().getResourceAsStream("db.propertites");        
    
          Properties pro = new Properties(); //map
          pro.load(instream);
          
          String url = pro.getProperty("url");
          String username = pro.getProperty("username");
            
          System.out.println(url);
          System.out.println(username);
            
        }
    
    }

    其中userDAO.class.getClassLoader

    得到类装载器

    因为他们都是在Classes文件夹下面,所以可以访问到该文件

    由于对数据库的操作方法有很多,不能每个方法里面都写这种,所以可以使用静态代码块的方式。

    public class userDAO {
        
        private static Properties dbconfig =new Properties();
        
        static{
            try {
                  InputStream instream =userDAO.class.getClassLoader().getResourceAsStream("db.propertites");
                  dbconfig.load(instream);
            } catch (Exception e) {
                throw new ExceptionInInitializerError(e);
            }
        }
    
        public void update() throws IOException {        
          System.out.println(dbconfig.getProperty("url"));        
        }
        
        public void find() throws IOException {        
                 
            }
        
        public void delete() throws IOException {        
                
            }
    
    }

     使用类装载器读取文件的弊端:

    1.文件不能太大,因为它是以装载类的方式一次性加入内存中

    2.类装载器只会加载一次,就是说不能显示文件的更新操作

    3.使用绝对路径读取

    如果需要读到实时数据,就不能通过类装载器来读文件,需要通过普通的文件路径的方式

    还是要通过类装载的方式来得到文件的位置

    public class DAO {
        
        public void update() throws IOException{
          
            String path = DAO.class.getClassLoader().getResource("db.properties").getPath();
            FileInputStream in= new FileInputStream(path);
            
            Properties pros = new Properties();
            pros.load(in);
            
            String url = pros.getProperty("url");    
    
        }
    
    }

     

  • 相关阅读:
    C# 控制台应用程序输出颜色字体[更正版]
    ORM for Net主流框架汇总与效率测试
    php 去掉字符串的最后一个字符
    bzoj1185 [HNOI2007]最小矩形覆盖 旋转卡壳求凸包
    bzoj [Noi2008] 1061 志愿者招募 单纯形
    bzoj1009 [HNOI2008] GT考试 矩阵乘法+dp+kmp
    扩展欧几里得(ex_gcd),中国剩余定理(CRT)讲解 有代码
    BZOJ 2103/3302/2447 消防站 树的重心【DFS】【TreeDP】
    hihocoder 1449 后缀自动机三·重复旋律6
    hihocoder 后缀自动机二·重复旋律5
  • 原文地址:https://www.cnblogs.com/tech-bird/p/3843832.html
Copyright © 2011-2022 走看看