Run the jar package to read the external configuration file

Case: This article mainly describes the linux system to execute the jar package to read the external configuration file of the same level directory of the jar package.
Method 1: Set the configuration file
by relative path (1) Create the configuration file conf.properties in the same level directory of the jar package and write the configuration data:

confData=data
1
(2) Start writing automated test code

//java project www.fhadmin.org
public class Test{
    public String getData() throws IOException {
        //Read configuration file
        Properties properties = new Properties();
        File file = new File("conf.properties");
        FileInputStream fis = new FileInputStream(file);
        properties.load (fis);
        fis.close();

        //Get configuration file data
        String confData = properties.getProperty("confData");
        System.out.println(confData);
    }
}


(3) Execute the jar package

java -jar jarNanexxx


Method 2: Set the configuration file
with absolute path to solve the problem: There is no problem when manually executing the jar package in the same level directory of the jar package using the method of relative path, but an error is reported when using the crontab file of the linux system to schedule regularly. Reason: because we manually execute a certain The script is executed in the current shell environment, and the program can find environment variables; while the system automatically executes task scheduling, it will not load any other environment variables except the default environment. Therefore, you need to specify all the environment variables required for the task to run in the crontab file, or use an absolute path in the program.
(1) Create a configuration file conf.properties in the same level directory of the jar package and write configuration data:

confData=data


(2) Start writing automated test code

//java project www.fhadmin.org
public class Test{
    public String getData() throws IOException {
       //Get the same level directory of the jar package
        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        String[] pathSplit = path.split("/");
        String jarName = pathSplit[pathSplit.length - 1];
        String jarPath = path.replace(jarName, "");
        String pathName=jarPath+"minhang.properties";
        System.out.println("Configuration file path:"+jarPath);

        //Read configuration file
        Properties properties = new Properties();
        File file = new File(pathName);
        FileInputStream fis = new FileInputStream(file);
        properties.load (fis);
        fis.close();

        //Get configuration file data
        String confData = properties.getProperty("confData");
        System.out.println(confData);
    }
}


(3) Execute the jar package

java -jar jarNanexxx

 


Guess you like

Origin blog.51cto.com/14622073/2665335