Home > Blockchain >  FileNotFoundException when reading properties file
FileNotFoundException when reading properties file

Time:08-07

I am facing this issue while reading property file. I searched a lot on the Internet but nothing worked. Below is the code and the image contains the path of the prop.properties file

package Utility;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropUtility {

    //private static Properties prop;
    
    private static Properties prop = new Properties();
    static {
        prop = new Properties();
        InputStream in = prop.getClass().getResourceAsStream("/resources/prop.properties");
        try {
            prop.load(in);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static String getProperty(String key) {
        return prop.getProperty(key);
    }
}

Screen capture of my IDE

CodePudding user response:

    [When you run the code, it cannot access your propertis file.
    You get a nullPointerException error when loading in from that one.
    Get your properties file like in the picture below Link[1](open and see image), put it in the project, then run your code. I also made a similar example with FileReader.
    Extract from the resource folder. You can read it that way if you import it into the project.
    Give this a try.][1]

  [1]: https://i.stack.imgur.com/d4xC6.jpg

CodePudding user response:

 public static void main(String[] args) throws IOException {
        FileReader reader= null;
        try {
            reader = new FileReader("prop.properties");
        } catch (FileNotFoundException ex) {
            throw new RuntimeException(ex);
        }

        Properties p=new Properties();
        p.load(reader);

        System.out.println(p.getProperty("user"));
        System.out.println(p.getProperty("password"));
    }
  • Related