There are three ways to obtain resource files

  • Get it using the ServletContext object
  • Get it using the ResourceBundle class
  • Use the class loader to obtain

Get a, B and C. perties in the figure respectively:

The file contents are as follows: A =a; b=b; c=c

Important: Note that the path to the file in the figure is not written directly from the ide, but from the location of the file after the project is published to Tomcat.

First, use the ServletContext object

Advantages: Any file, any path Disadvantages: Must have a Web environment

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

1.1 Obtaining Resources in the Web directory B. Perties

Write: / p. roperties

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();
    }
    /** * Obtain the resource b. perties from the web, and check that the file is published to the tomcat location as /b. perties */
    public void getWebResource(a){
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/b.properties");
        // The path to the file is: D: WorkSpaces\IDEAWS\tomcatdemo\out\artifacts\tomcatdemo_war_exploded\ b.exploded ties
        System.out.println("The file path is:"+realPath);
        Properties properties = new Properties();
        try {
            properties.load(new FileReader(realPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Object b = properties.get("b");
        // The obtained key is: b
        System.out.println("The key obtained is:"+b);
    }

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

CATALINA_BASE = C:\Users\HCX\.IntelliJIdea2017.2\ System \tomcat\Tomcat_8_5_0_tomcatdemo

The differences between CATALINA_HOME and CATALINA_BASE are as follows: CATALINA_HOME is the Tomcat installation directory and CATALINA_BASE is the Tomcat working directory. If you want to run multiple instances of Tomcat, but do not want to install multiple copies of Tomcat software. You can then configure multiple working directories, with each running instance owning a single working directory but sharing the same installation directory. For details, please refer to my previous Tomcat article, which describes how the application is deployed: blog.csdn.net/CSDN_GIA/ar…

/b.properties

1.2 Obtaining resources in the WEB-INF directory C. perties

As you can see from the previous example, the path for the server represented by/is: D: WorkSpaces\IDEAWS\ Tomcatdemo \out\artifacts\tomcatdemo_war_exploded

/WEB-INF/c.properties

    /**
     * 获取WEB-INF下资源c.properties
     */
    public void getWebINFOResource(a) {
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/WEB-INF/c.properties");
        // The path to the file is: D: WorkSpaces\IDEAWS\tomcatdemo\out\artifacts\tomcatdemo_war_exploded\ web-INF \ c.exploded ties
        System.out.println("The file path is:" + realPath);
        Properties properties = new Properties();
        try {
            properties.load(new FileReader(realPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Object c = properties.get("c");
        // The key is c
        System.out.println("The key obtained is:" + c);
    }
Copy the code

1.3 Obtaining a.properties resources in the SRC directory

All SRC resources will be placed in the classes directory of the WEB-INF directory: / web-INF /classes/ a.perties

    public void getSrcResource(a) {
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/WEB-INF/classes/a.properties");
        // The path to the file is: D: WorkSpaces\IDEAWS\tomcatdemo\out\artifacts\tomcatdemo_war_exploded\ web-INF \classes\ a.exploded ties
        System.out.println("The file path is:" + realPath);
        Properties properties = new Properties();
        try {
            properties.load(new FileReader(realPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Object a = properties.get("a");
        // Obtain the key value: a
        System.out.println("The key obtained is:" + a);
    }
Copy the code

Second, use the ResourceBundle class to fetch

Advantages: Simple and convenient Disadvantages:

  • Only the properties file can be retrieved
  • You can only fetch non-Web resources (SRC directories)

ResourceBundle class: This class (abstract class) is dedicated to loading resources and can also handle internationalization

2.1 Obtaining a. perties resources in the SRC directory

    public void getSrcResource(a) {
        // Get the ResourceBundle object (specifically used to get information about the properties file, so no suffix is added. Properties)
        ResourceBundle resourceBundle = ResourceBundle.getBundle("a");
        String a = resourceBundle.getString("a");
        System.out.println("src下资源文件:" + a);

        // Get the ResourceBundle object (specifically used to get information about the properties file, so no suffix is added. Properties)
        ResourceBundle resourceBundle2 = ResourceBundle.getBundle("com.hcx.web.d");
        String d = resourceBundle2.getString("d");
        System.out.println("src下资源文件:" + d);
    }
Copy the code

Third, use the class loader to obtain

Advantages: Arbitrary file, arbitrary path disadvantages: writing a little trouble

Class loaders: Java, to compile this source code first use the command javac to compile it into a.class file, the.class file is located on the hard disk, at runtime, need to load the.class file into the virtual machine to run, 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 file

How to get the class loader

  1. Class name: classname.class.getClassLoader ()

  2. Pass the object: this.getClass().getClassLoader()

  3. Class.forname () : class.forname (” Class name “).getClassLoader()

Note: this getClass (). GetClassLoader () getResource (“/”); Load resources in the classes directory:

3.1 Obtaining Resources in the Web directory B. Perties

    public void getWebResourceByClassLoader(a){
        / / 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);

    }
Copy the code

3.2 Obtaining resources in the WEB-INF directory C. perties

    public void getWebInfoResourceByClassLoader(a){
        / / 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);
    }
Copy the code

3.3 Obtaining a.properties resources in the 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(a){
        // Get the class loader:
        / * * * 1. By the name of the class: this this = GetResourceFileServlet. Class. GetClassLoader (); ClassLoader = this.getClass().getClassLoader(); * 3. Pass 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); }}Copy the code