Some methods for reading configuration files in java, getResourceAsStream and direct FileInputStream, and the working directory

configured by System.getProperty("user.dir") are located under /src/ Listed by the above bloggers, you can take a step by step, that is, the following situations

1. Path: src/aa.xml

2. Under the same package under src

3 Located in src under different packages

But the blogger's project is a web project, and the configuration file is placed in the src file. It is easy to update due to the cache,

so I put the configuration file at @@/WebContent/WEB-INF/Under the folder, you can put it in other non-web projects or you can put it in /cfg/ 

at this time. The configuration file is not in the src folder

Directly used to file stream

InputStream is = new FileInputStream(System.getProperty("user.dir") + "/WebContent/WEB-INF/" + resource);

Note that you need to configure System.getProperty("user.dir") to get the working directory:

Step: Right-click any project, "Debug As", sub-option "Debug Configurations...", Pop-up window:

Debug Configuration
Debug Configuration

Click the second tab "Arguments",

Arguments
Arguments

find the "Working directory:" at the bottom, generally the default is Default, if it does not match You can also set their own Other bloggers use the "Variables" in the "project_path"

Variables
Variables

of which there are many other variables can choose their own utility.

I am using mybatis to write the configuration file new FileInputStream used by the tool class MybatisJDBC. My configuration file mybatis-config.xml is under /WebContent/WEB-INF/:

public class MybatisJDBC
{

/**
     * 获取SqlSessionFactory
     * @return SqlSessionFactory
     */
    public static SqlSessionFactory getSqlSessionFactory()
    {
        String resource = "mybatis-config.xml";
        SqlSessionFactory factory = null;
        try
        {
            InputStream is = new FileInputStream(
                    System.getProperty("user.dir") + "/WebContent/WEB-INF/" + resource);

            // System.out.println(MybatisJDBC.class.getClassLoader().getResourceAsStream(resource)); //null
            factory = new SqlSessionFactoryBuilder().build(is);
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return factory;
    }

}

However, if your configuration file is under /src/, you can do this: (anyway, the blogger gets null, because it is not under /src/)

public class MybatisJDBC
{

/**
* Get SqlSessionFactory
     * @return SqlSessionFactory
     */
    public static SqlSessionFactory getSqlSessionFactory()
    {
        String resource = "mybatis-config.xml";
        InputStream is =MybatisJDBC.class.getClassLoader().getResourceAsStream(resource);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        return factory;
    }

}