Search code examples
javaproperties-file

Java Writing to Properties File Not Working


For some reason, the following code, which in my program is surrounded by a try-catch statement, is not working, as it continues to throw a NumberFormatException, and also wipes the properties file clean of information. Help is appreciated.

        File propFile = new File("path\to\file\properties.properties");
        FileOutputStream outStream  = new FileOutputStream(propFile);
        FileInputStream inStream = new FileInputStream(propFile);

        Properties prop = new Properties();
        prop.load(inStream);

        out.println(prop.getProperty("entryID"));

        prop.setProperty("entryID", Integer.toString(Integer.parseInt(prop.getProperty("entryID"))+1));

        prop.store(outStream, "");

Solution

  • Just change line of sequence, You are creating FileOutStream Object before you read the content

    Please find attached working snippet

    File propFile = new File("path\to\file\properties.properties");

        FileInputStream inStream = new FileInputStream(propFile);
    
        Properties prop = new Properties();
        prop.load(inStream);
    
        System.out.println(prop.getProperty("entryID"));
    
        prop.setProperty("entryID", Integer.toString(Integer.parseInt(prop.getProperty("entryID"))+1));
        FileOutputStream outStream  = new FileOutputStream(propFile);
        prop.store(outStream, "");