maximus
maximus

Reputation: 11544

How to load a properties file from the root directory?

I am currently loading a properties file like this:

private Properties loadProperties(String filename) throws IOException{
        InputStream in = ClassLoader.getSystemResourceAsStream(filename);
        if (in == null) {
            throw new FileNotFoundException(filename + " file not found");
        }
        Properties props = new Properties();
        props.load(in);
        in.close();
        return props;
    }

However, at the moment my file lays at the scr\user.properties path.

But when I want to write to a properties file:

properties.setProperty(username, decryptMD5(password));
        try {
            properties.store(new FileOutputStream("user.properties"), null);
            System.out.println("Wrote to propteries file!" + username + " " + password);

That piece of code generates me a new file at the root folder level of my project.

BUT I want to have one file to write\read.

Therefore how to do that?

PS.: When I want to specify the path I get "Not allowed to modify the file..."

Upvotes: 1

Views: 4466

Answers (1)

Milind V. Acharya
Milind V. Acharya

Reputation: 411

The reason a new file is created because you are trying to create a new file when you are writing. You should first get handle to the user.properties that you want to write to as File object and then try to write to it.

The code would look something along the lines of

properties.setProperty(username, decryptMD5(password));
try{
    //get the filename from url class
    URL url = ClassLoader.getSystemResource("user.properties");
    String fileName = url.getFile();

    //write to the file
    props.store(new FileWriter(fileName),null);
    properties.store();
}catch(Exception e){
    e.printStacktrace();
}

Upvotes: 2

Related Questions