简体   繁体   中英

Writing to .properties file in java web application

I was trying to write a key value pair to a chat.properties file in java .My function to do so is something like this :

public void WritePropertiesFile() throws FileNotFoundException, IOException {
    File file = 
        new File("C:\\Users\\admin\\Desktop\\SharedCrpto1\\web\\chat.properties");
    Properties configProperty = new Properties();
    InputStream in = new FileInputStream(file);
    configProperty.load(in);    
    configProperty.setProperty("newKey", "newValue");
    in.close();
    OutputStream outt = new FileOutputStream(file); 
    configProperty.store(outt, "my data");
    outt.close();
}

But its not working and the data is not being entered in the file.Please help to resolve the problem.

Try this code:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

public class MakeEntryInPropertyFile {
  public static void main(String[] args) {

    Properties prop = new Properties();
    OutputStream output = null;

    try {

        output = new FileOutputStream("C:\\Users\\admin\\Desktop\\SharedCrpto1\\web\\chat.properties");
        prop.setProperty("newKey", "newValue");
        prop.store(output, null);
    } catch (IOException io) {
        io.printStackTrace();
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  }
}

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