6

I want to write into a *.properties file. Thats my code how I do this:

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

I do not get an exception, but I also do not get the output written into the file.

Here is also my file-structure:

enter image description here

I appreciate your answer!!!

UPDATE

I load my properties file with:

    InputStream in = ClassLoader.getSystemResourceAsStream(filename);

My question is, how to load it from a specific path?

Here is my "new" File Structure:

enter image description here

maximus
  • 11,264
  • 30
  • 93
  • 124
  • 1
    I have tested your code and my properties file is created in my working directory. Of course, with your file structure that is wrong. I guess that you must use a path to your file instead of just using the file name – ElderMael Nov 10 '12 at 13:49
  • when I use the path like \\user.properties I get "You have no rights to access the file..." – maximus Nov 10 '12 at 13:51

1 Answers1

4

Here is my testing code:

@Test
public void fileTest() throws FileNotFoundException, IOException {

    File file = null;

    Properties props = new Properties();

    props.setProperty("Hello", "World");

    URL url = Thread.currentThread().getContextClassLoader()
            .getResource("exceptions/user.properties");

    try {
        file = new File(url.toURI().getPath());

        assertTrue(file.exists());
    } catch (URISyntaxException e) {

        e.printStackTrace();
    }

    props.store(new FileOutputStream(file), "OMG, It werks!");

}

It does creates and rewrites a file in my target/classes/exceptions directory (in a maven/eclipse proyect) so I guess it really works, but of course that is not tested in a JAR file.

Here is the file:

#OMG, It werks!
#Sat Nov 10 08:32:44 CST 2012
Hello=World

Also, check this question: How can i save a file to the class path

So maybe what you want to do never will work.

Community
  • 1
  • 1
ElderMael
  • 7,000
  • 5
  • 34
  • 53
  • I am printint he URL for checking and it is giving me as :/C:/Users/IBM_ADMIN/workspace/A_Migration_final/bin/common/props_1.dat but the correct URL is C:\Users\IBM_ADMIN\workspace\A_Migration_final\src\common\props.dat It's writing in the bin file, do you think it would give the correct values when queried ? – The_Lost_Avatar Oct 13 '13 at 19:12