Java resource files acquired in three ways

There are three ways to obtain the resource file

  • Using ServletContext object gets
  • ResourceBundle class employed to obtain
  • Using class loader acquires

FIG respectively acquire the a, b, c.properties:

image.png

File contents are: a = a; b = b; c = c

Important: Note that the file path to get the figure written, not looking directly at the location of ide, but we should look to the tomcat project release position after the file is located.

First, the use ServletContext object gets

Pros: any file, any path drawback: You must have a web environment

Get real file (server) path:String getRealPath()

1.1 access to resources b.properties web directory

Writing:/b.properties

package com.hcx.web.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

/**
 * Created by hongcaixia on 2019/11/19.
 */
@WebServlet("/getResourceFileServlet")
public class GetResourceFileServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        getWebResource();
    }
    /**
     * 获取web下的资源b.properties,查看文件发布到tomcat的位置为/b.properties
     */
    public void getWebResource(){
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/b.properties");
        //文件的路径是:D:\WorkSpaces\IDEAWS\tomcatdemo\out\artifacts\tomcatdemo_war_exploded\b.properties
        System.out.println("文件的路径是:"+realPath);
        Properties properties = new Properties();
        try {
            properties.load(new FileReader(realPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Object b = properties.get("b");
        //获取到的key是:b
        System.out.println("获取到的key值是:"+b);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

复制代码

After the start of the project to find CATALINA_BASE value from the log:C:\Users\HCX\.IntelliJIdea2017.2\system\tomcat\Tomcat_8_5_0_tomcatdemo

CATALINA_BASE.png

CATALINA_HOMEAnd CATALINA_BASEthe difference between: Simply put, CATALINA_HOMEthe Tomcat installation directory, CATALINA_BASEis Tomcat working directory. If you want to run multiple instances of Tomcat, Tomcat but do not want to install multiple copies of the software. You can configure multiple working directory for each running instance exclusively a working directory, but share the same installation directory. Details can refer to the article I wrote before Tomcat, which describes the deployment of the application: blog.csdn.net/CSDN_GIA/ar...

Posted path to the server .png

image.png
So, the next b.properties file located in the root directory of the server, written as /b.properties

1.2 c.properties access to resources under WEB-INF directory

image.png

As can be seen from the previous example, / server path is represented by:D:\WorkSpaces\IDEAWS\tomcatdemo\out\artifacts\tomcatdemo_war_exploded

image.png
So resources under WEB-INF written as: /WEB-INF/c.properties

    /**
     * 获取WEB-INF下资源c.properties
     */
    public void getWebINFOResource() {
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/WEB-INF/c.properties");
        //文件的路径是:D:\WorkSpaces\IDEAWS\tomcatdemo\out\artifacts\tomcatdemo_war_exploded\WEB-INF\c.properties
        System.out.println("文件的路径是:" + realPath);
        Properties properties = new Properties();
        try {
            properties.load(new FileReader(realPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Object c = properties.get("c");
        //获取到的key值是:c
        System.out.println("获取到的key值是:" + c);
    }
复制代码

1.3 access to resources a.properties src directory

image.png

All resources will be placed under src future classes directory under the WEB-INF directory of writing:/WEB-INF/classes/a.properties

    public void getSrcResource() {
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/WEB-INF/classes/a.properties");
        //文件的路径是:D:\WorkSpaces\IDEAWS\tomcatdemo\out\artifacts\tomcatdemo_war_exploded\WEB-INF\classes\a.properties
        System.out.println("文件的路径是:" + realPath);
        Properties properties = new Properties();
        try {
            properties.load(new FileReader(realPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Object a = properties.get("a");
        //获取到的key值是:a
        System.out.println("获取到的key值是:" + a);
    }
复制代码

Second, the use ResourceBundle class to obtain

Pros: Easy Disadvantages:

  • You can only pick up properties file
  • Can only pick up resources in non-web environment (ie the src directory)

ResourceBundle class: class (abstract class) dedicated to load resources, it can also handle some of the international stuff

2.1 access to resources a.properties src directory

image.png

    public void getSrcResource() {
        //获取ResourceBundle对象(专门用来获取properties文件的信息,所以不用加后缀名.properties)
        ResourceBundle resourceBundle = ResourceBundle.getBundle("a");
        String a = resourceBundle.getString("a");
        System.out.println("src下资源文件:" + a);

        //获取ResourceBundle对象(专门用来获取properties文件的信息,所以不用加后缀名.properties)
        ResourceBundle resourceBundle2 = ResourceBundle.getBundle("com.hcx.web.d");
        String d = resourceBundle2.getString("d");
        System.out.println("src下资源文件:" + d);
    }
复制代码

Third, using class loader acquires

Pros: any file, any path Disadvantages: somewhat cumbersome to write

Class loader: a java file, then write a good source extension is .java, you want to first use the source code compiler command javac to compile it into a .class file, the .class file is located on your hard disk, at run time, you need to the .class file is loaded into the virtual machine is running, use the class loader to load the main purpose of the class loader is to load the bytecode file into memory, and then run the bytecode files

Get the class loader mode

  1. By class name: 类名.class.getClassLoader()

  2. By subject: this.getClass().getClassLoader()

  3. Class.forName(): Class.forName("类名").getClassLoader()

Note: this.getClass().getClassLoader().getResource("/");go to class path load resources, namely the classes directory:

classes directory .png

3.1 access to resources b.properties web directory

    public void getWebResourceByClassLoader(){
        //url:file:/D:/WorkSpaces/IDEAWS/tomcatdemo/out/artifacts/tomcatdemo_war_exploded/WEB-INF/classes/
        URL url = this.getClass().getClassLoader().getResource("/");
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("../../b.properties");

        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String b = properties.getProperty("b");
        System.out.println(b);

    }
复制代码

3.2 c.properties access to resources under WEB-INF directory

    public void getWebInfoResourceByClassLoader(){
        //url:file:/D:/WorkSpaces/IDEAWS/tomcatdemo/out/artifacts/tomcatdemo_war_exploded/WEB-INF/classes/
        URL url = this.getClass().getClassLoader().getResource("/");
        InputStream resourceAsStream1 = this.getClass().getClassLoader().getResourceAsStream("../../WEB-INF/c.properties");

        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String c = properties.getProperty("c");
        System.out.println(c);
    }
复制代码

3.3 access to resources a.properties src directory

package com.hcx.web.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 * Created by hongcaixia on 2019/11/19.
 */
@WebServlet("/getResourceFileServlet")
public class GetResourceFileServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        getSrcResourceByClassLoader();
    }

    public void getSrcResourceByClassLoader(){
        //获取类加载器方式:
        /**
         * 1.通过类名:ClassLoader classLoader = GetResourceFileServlet.class.getClassLoader();
         * 2.通过对象:ClassLoader classLoader = this.getClass().getClassLoader();
         * 3.通过Class.forName():ClassLoader classLoader = Class.forName("GetResourceFileServlet").getClassLoader();
         */
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("a.properties");
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String a = properties.getProperty("a");
        System.out.println(a);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

复制代码

Guess you like

Origin juejin.im/post/5ddd1c59f265da05e7738c4b