简体   繁体   中英

Unable to read a properties file in IntelliJ

My folder structure is :

Main
  |
  .idea
  resources 
  src
     |
      main
        |
        java
          |
          com.read.properties
                |
                config.properties 
                a.java

my code in a.java is :

Properties prop = new Properties();
    InputStream input = null;

    try {

        String filename = "config.properties";
        input = getClass().getClassLoader().getResourceAsStream(filename);
        if (input == null) {
            System.out.println("Sorry, unable to find " + filename);
            return Response.status(400).build();
        }

        prop.load(input);

        Enumeration<?> e = prop.propertyNames();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            String value = prop.getProperty(key);
            System.out.println("Key : " + key + ", Value : " + value);
        }

    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

I am not able to read the properties file , I keep getting an IO error . I tried changing the default classpath

from Run->Edit Configurations .

When I try something similar in eclipse , I can read the file quite easily leading me to believe that I have some configuration in intelliJ wrong . I would be very grateful if somebody could point me to the right direction

I'm not sure about this, but in my IDEA (Maven) projects I keep my resources under src/main|test/resources and I can read them just fine:

src
   main
       resources
           path
               file


getClass().getClassLoader().getResourceAsStream("path/file");

You need to specify the "full" path to the file though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM