简体   繁体   中英

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, "");

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, "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM