1. 程式人生 > 程式設計 >Java中獲取資原始檔三種方式

Java中獲取資原始檔三種方式

獲取資原始檔有三種方式

  • 採用 ServletContext物件獲取
  • 採用ResourceBundle類來獲取
  • 採用類載入器獲取

分別獲取圖中的a、b、c.properties:

image.png

檔案內容分別是:a=a;b=b;c=c

重點:注意獲取圖中檔案的路徑寫法,不是直接看ide中的位置,而是要看專案釋出到tomcat之後該檔案所在的位置。

一、採用 ServletContext物件獲取

優點: 任意檔案,任意路徑 缺點: 必須有web環境

獲取檔案真實(伺服器)路徑:String getRealPath()

1.1 獲取web目錄下資源b.properties

寫法:/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,IOException { this.doPost(request,response); } } 複製程式碼

專案啟動後從日誌中找到CATALINA_BASE值:C:\Users\HCX\.IntelliJIdea2017.2\system\tomcat\Tomcat_8_5_0_tomcatdemo

CATALINA_BASE.png

CATALINA_HOMECATALINA_BASE的區別: 簡單的說,CATALINA_HOME是Tomcat的安裝目錄,CATALINA_BASE是Tomcat的工作目錄。 如果想要執行Tomcat的多個例項,但是不想安裝多個Tomcat軟體副本。那麼可以配置多個工作目錄,每個執行例項獨佔一個工作目錄,但是共享同一個安裝目錄。 詳細介紹可以參考我之前寫的Tomcat文章,裡面介紹了應用程式的部署方式:blog.csdn.net/CSDN_GIA/ar…

釋出到伺服器的路徑.png

image.png
所以,b.properties檔案位於伺服器的根目錄下,寫法為/b.properties

1.2 獲取WEB-INF目錄下資源c.properties

image.png

從上一個例子可以看出,/代表的伺服器的路徑是:D:\WorkSpaces\IDEAWS\tomcatdemo\out\artifacts\tomcatdemo_war_exploded

image.png
所以 WEB-INF下資源寫法為:/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 獲取src目錄下資源a.properties

image.png

src下的所有資源將來會被放到WEB-INF目錄下的classes目錄下 寫法:/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);
    }
複製程式碼

二、採用ResourceBundle類來獲取

優點:簡單方便 缺點:

  • 只能拿取properties檔案
  • 只能拿取非web環境下的資源(即src目錄下的)

ResourceBundle類:該類(抽象類)專門用來載入資源,還可以處理一些國際化的東西

2.1 獲取src目錄下資源a.properties

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);
    }
複製程式碼

三、採用類載入器獲取

優點: 任意檔案,任意路徑 缺點: 編寫稍顯麻煩

類載入器: 一個java檔案,編寫好之後是原始碼,字尾名是.java,要將這個原始碼首先採用編譯命令javac把其編譯為.class檔案,該.class檔案位於硬碟上,在執行時,需要把.class檔案載入到虛擬機器器裡執行,就用類載入器來載入,類載入器的主要目的就是將位元組碼檔案載入到記憶體裡,然後執行位元組碼檔案

獲取類載入器的方式

  1. 通過類名 : 類名.class.getClassLoader()

  2. 通過物件: this.getClass().getClassLoader()

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

注意: this.getClass().getClassLoader().getResource("/");是去類路徑去載入資源,即classes目錄下:

classes目錄.png

3.1 獲取web目錄下資源b.properties

    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 獲取WEB-INF目錄下資源c.properties

    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 獲取src目錄下資源a.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.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,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,response);
    }
}

複製程式碼