coding++:java 如何获取resources下的文件

当我们想要获取mysql.properties、oracle.properties、bayonetConfig.txt文件里面内容的时候,我们一般会采用不同的方式,面对是properties,那么我所采用的是。

ResourceBundle bundle = ResourceBundle.getBundle(resourceFile);
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String username = bundle.getString("username");
String password = bundle.getString("password");

其中resourceFile只需要配置文件的前缀名称,也就是说,不需要properties这样的后缀名称。

对于TXT文件,我们一般需要一行一行读取。

public final InputStream INPUTSTREAM = this.getClass().getClassLoader().getResourceAsStream("bayonetConfig.txt");

public final InputStream INPUTSTREAM = this.getClass().getClassLoader().getResourceAsStream("classpath:config/data/students.txt");

在需要的地方使用:

private final String classpathKey = "classpath:";
    private final String configPath = "classpath:config/data/students.txt";

    @RequestMapping("save")
    public String save() {
        BufferedReader reader = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader=null;
        try {
            if (configPath.startsWith(classpathKey)) {
                inputStream =this.getClass().getClassLoader().getResourceAsStream(configPath.substring(classpathKey.length()));
            } else {
                inputStream = new FileInputStream(configPath);
            }
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);
            //迭代数据
            String temp = null;
            while ((temp = reader.readLine()) != null) {
                System.out.println(temp);
            }
            reader.close();
            inputStreamReader.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "OK";

    }

注意事项:

在读取bayonetConfig.txt时候,使用:

    public final  String BAYONET_PATH = this.getClass().getClassLoader().getResource("bayonetConfig.txt").getPath();

能获取文件的路径,但是一旦我打包成jar的时候,就会提示我找不到文件。 我在查阅了相关的博客后,得知了一些原因。

1、当我在IDEA里面进行调试的时候,文件是真实存在于磁盘的某个路径的,所以能正常的进行读取

2、而打成jar后,文件是存在于jar文件里面的资源文件,在磁盘是没有真实的路径的,所以无法通过

正确的做法是通过流的方式来进行获取:

public final InputStream INPUTSTREAM = this.getClass().getClassLoader().getResourceAsStream("bayonetConfig.txt");

另外一种方式:

ClassPathResource resource = new ClassPathResource("export/aaa.txt");
InputStream inputStream = resource.getInputStream();
原文地址:https://www.cnblogs.com/codingmode/p/12773262.html