Denis Kulagin
Denis Kulagin

Reputation: 8906

Java: load and edit properties file on classpath

I would like to persist some properties to property-file in case they were changed during a program run. Now I am trying to do so:

Properties properties = new Properties();

    try (FileInputStream in = new FileInputStream("classpath:app.properties")) {
        properties.load(in);
    } catch (IOException e) {
        logger.error("", e);
    }

    properties.setProperty("word", "abc");

    try (FileOutputStream out = new FileOutputStream("classpath:app.properties")) {
       properties.store(out, null);
    } catch (IOException e) {
        logger.error("", e);
    }

But it doesn't seem to work. What am I doing wrong?

Upvotes: 1

Views: 6281

Answers (3)

Ashish Shetkar
Ashish Shetkar

Reputation: 1467

If you want to stick to properties file handling through class path - you can certainly use below code as it is , i think it is simplest way of handling file in class path for both - reading and writing purpose

try{

    InputStream in =   this.getClass().getResourceAsStream("/suggest.properties");
    Properties props = new Properties();
    props.load(in);
    in.close();


    URL url = this.getClass().getResource("/suggest.properties");
    File fileObject = new File(url.toURI());

    FileOutputStream out = new FileOutputStream(fileObject);

    props.setProperty("country", "america");
    props.store(out, null);
    out.close();

    }catch(Exception e)
    {
        System.out.println(e.getMessage());
    }

Upvotes: 0

pbespechnyi
pbespechnyi

Reputation: 2291

To be able to read and write properties file, which are in the resources folder (in standard maven project structure) you can use this:

// of course, do not forget to close the stream, after your properties file has been read.
properties.load(Runner.class.getClassLoader().getResourceAsStream("app.properties"));

After you modified the properties file, you can use something like:

Runner.class.getClassLoader().getResource("app.properties").getFile()

to get absolute path to you file.

P.S. Just to be sure you're checking correct file. You shouldn't check file that is in your resources folder. The modified file will be placed in the root folder with you classes, like target or out.

Upvotes: 3

Gravedigg74
Gravedigg74

Reputation: 11

If the file is in the same directory as your program, you don't need the classpath part.

Properties properties = new Properties();

try (FileInputStream in = new FileInputStream("app.properties")) {
    properties.load(in);
} catch (IOException e) {
    logger.error("", e);
}

properties.setProperty("word", "abc");

try (FileOutputStream out = new FileOutputStream("app.properties")) {
   properties.store(out, null);
} catch (IOException e) {
    logger.error("", e);
}

Otherwise if the file is within your jar, you would have to repackage the jar

Upvotes: 1

Related Questions