About the use of Object.class.getResourceAsStream method to read files

Attach the code first.

package com.property;
 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
 
 
public class Test {
    
    
	
	
	public static int getSocketPort(String tomcatpath, String propertyName) {
    
    
 
        Properties prop = new Properties();
        InputStream in = null;
        String socketPort = null;
 
        try {
    
    
 
            // 加载tomcatpath.properties文件
            in = Object.class.getResourceAsStream(tomcatpath);
            prop.load(in);
 
            Enumeration it = prop.propertyNames();
            while (it.hasMoreElements()) {
    
    
                String key = (String) it.nextElement();
 
                if (propertyName.equals(key)) {
    
    
                    socketPort = prop.getProperty(key);
                    break;
                }
            }
 
        } catch (FileNotFoundException e1) {
    
    
 
            throw new RuntimeException(e1);
 
        } catch (IOException e) {
    
    
            // TODO Auto-generated catch block
            // e.printStackTrace();
            throw new RuntimeException(e);
 
        } finally {
    
    
            try {
    
    
                if (in != null) {
    
    
                    in.close();
                }
            } catch (IOException e) {
    
    
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
 
        return Integer.parseInt(socketPort);
    }
}
package com.property;
 
public class Main {
    
    
 
	public static void main(String[] args) {
    
    
		int socketPort = Test.getSocketPort("/test/tomcatpath.properties", "tomcat_port");
		System.out.println(socketPort);
	}
 
}

When using the Object.class.getResourceAsStream method, create the folder configss in the same level directory as src, create the log4j.properties file and the folder test under the folder, and create the file tomcatpath.properties under the test folder, as shown in the figure

insert image description here

At this time, when the main function is executed, the program will directly report an error. After research, the problem is found as follows:

It is necessary to execute build path–use as source folder for the configss folder, and the result is as shown in the figure below

img

At this point, execute the main function, the method will succeed, and output the value of tomcat_port.

Reason: When the build path–use as source folder is executed on the configss folder, the configuration files under the configss folder can be directly read and written by the class with a relative path. (It has nothing to do with the name of the configss folder itself)

File - Get the input stream inputstream of the file under the resource directory: getResourceAsStream()

Two ways to use:

① T.class.getResourceAsStream(path) : If the path does not start with '/', the default is to get resources from the package where this class is located, and if the path starts with '/', it will get resources from the root of ClassPath. It just constructs an absolute path through path, and ClassLoader finally obtains resources.

 String path="/application.yml";
 InputStream resourceAsStream = A.class.getResourceAsStream(path);
 InputStream resourceAsStream = this.getClass().getResourceAsStream(path);

② T.class.getClassLoader().getResourceAsStream(path): The default is to obtain resources from the root of ClassPath, path cannot start with '/', and ClassLoader finally obtains resources.

 String path="/application.yml";
 InputStream resourceAsStream1 = A.class.getClassLoader().getResourceAsStream(path);

③ Obtain the attribute list from the input file stream:

insert image description here
bash_cmds.properties file:

modifyIp=nmcli con modify "$1" "$2" "$3" ipv4.method manual
getDeviceDetail=nmcli device "$1"

Load the bash_cmds.properties file and get a list of properties:

public class Bash {
    
    
    public static void main(String[] args) {
    
    
        String cmdFileName = "/bash_cmds.properties";
        // 获取输入流
        InputStream inputStream = Bash.class.getResourceAsStream(cmdFileName);
        Properties COMMANDS = new Properties();
        try {
    
    
            // 从输入文件流中获取属性列表
            COMMANDS.load(inputStream);
            System.out.println(COMMANDS.getProperty("getDeviceDetail"));
            System.out.println(COMMANDS.get("modifyIp"));
        } catch (IOException e) {
    
    
            throw new RuntimeException("Load file " + cmdFileName + " failed!");
        } catch (NullPointerException npe) {
    
    
            throw new RuntimeException("File " + cmdFileName + " may not exist in classpath!");
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_43842093/article/details/130663864