Update properties file values with form values - java

I am having a jsp file in which I load the existing values present in properties file. When the user edit the existing value and submit the form, the properties file must be updated with that values. Can anyone help me with this? I am using only java.

FileInputStream in = new FileInputStream("Example.properties");
Properties props = new Properties();
props.load(in);
Now Update it
FileOutputStream outputStream = new FileOutputStream("Example.properties");
props.setProperty("valueTobeUpdate", "new Value");
props.store(outputStream , null);
outputStream .close();
Another way of achieving same is explained at
http://crunchify.com/java-properties-files-how-to-update-config-properties-file-in-java/

PropertiesConfiguration config = new PropertiesConfiguration("/Users/abc/Documents/config.properties");
config.setProperty("Name", "abcd");
config.setProperty("Email", "abcd#gmail.com");
config.setProperty("Phone", "123456");
config.save();

here is an example of how to update your properties file :
public class PropertyManager {
private static Properties prop = new Properties();
private static String PROPERTY_FILENAME = "config.properties";
public static void main(String[] args) {
loadProperty();
System.out.println(prop.get("myProperty"));
updateProperty("myProperty", "aSecondValue");
}
public static void loadProperty(){
InputStream input = null;
try {
input = new FileInputStream(PROPERTY_FILENAME);
// load a properties file
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void updateProperty(String name, String value){
OutputStream output = null;
try {
output = new FileOutputStream(PROPERTY_FILENAME);
// set the properties value
prop.setProperty(name, value);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I let you change "new Properties", by the way you retrieve it.

Related

How to set right path of property file?

I have a problem I can't resolve.
I need to read properties file, but can't set right path.
Documentation of java.io.File is saying that I have to set in from the src/...
It doesnt work, I did a path from current file and have the same problem.
EXCEPTION IS : FileNotFound
PropertyReader class:
public final class PropertyReader {
private Properties prop = new Properties();
private InputStream input = null;
public Properties getProperties(File file) {
try {
input = new FileInputStream(file);
// load a properties file
prop.load(input);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != input) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return prop;
}
}
And ApplicationController.class which uses PropertyReader:
#RequestMapping(value = "/result", method = RequestMethod.GET)
public String resultPage(ModelMap model) {
//Getting property with key "path"
model.addAttribute("path", new PropertyReader().getProperties(file).getProperty("path"));
return "result";
If I'm setting path from C://.. it works fine.
Thank you much and have a nice day!
Try to use Following example to read property file.
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class App {
public static void main(String[] args) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("mysqldb"));
System.out.println(prop.getProperty("dbuser"));
System.out.println(prop.getProperty("dbpassword"));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Its also depends on the framework that you are using like SpringMVC, JSF and Struts. All these framework have their own shortcut ways to access property files.
I resolved it by using annotations #PropertySource and #Value()
For example:
//There could be any folder
#PropertySource("classpath:file.properties")
public class AnyClass {
//There could be any property
#Value("${some.property}")
private String someValue;
}

Java getting a certain property from the config.properties file that exists more than once

I have config.properties file that contains names.
Say it looks as such:
#Client1 properties
1Client=Client1
1someproperty=someproperty
#Client2 properties
2Client=Client1
2someproperty=someproperty
What I am trying to achieve is only getting the client names in a DefaultListModel so I can add them to a list. I have tried the following:
public static DefaultListModel SetVM() {
int clientCode = 1;
DefaultListModel vm_list = new DefaultListModel();
Properties props = new Properties();
FileInputStream fis = null;
try {
props.load(fis);
fis = new FileInputStream("config.properties");
//if (statement to see if props contains clientCode) {
String vmClient = props.getProperty(DatabaseCode + "CLIENT");
vm_list.addElement(vmClient);
//}
} catch (Exception e) {
}
return vm_list;
}
I was thinking along the line of for(Object obj : fis), but that is not possible. The other option was using an iterator as discribed here.
Though I cannot grasp how to get a certain property.
Try this. Using Properties entrySet which gives you the key and value for each property.
#Test
public void testClient () throws IOException {
DefaultListModel<String> vm_list = new DefaultListModel<String>();
Properties props = new Properties();
FileInputStream fis = null;
fis = new FileInputStream("config.properties");
props.load(fis);
for (Entry<Object, Object> entry : props.entrySet()) {
System.out.println("Entry key:" + entry.getKey() + " value:" + entry.getValue());
String key = (String)entry.getKey();
if (key.endsWith("Client")) {
vm_list.addElement(key); // maybe want to add entry.getValue() instead
}
}
// return vm_list;
}
Try something like this. Just used the regex to identify the client property.
Hope this helps.
Properties properties = new Properties();
try
{
properties.load(new FileInputStream("config.properties"));
for(String key : properties.stringPropertyNames()){
if(key.matches("(\\d+)Client")){
//add to arrayList
}
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
Try this:-
Manage with a domain class
public class Client {
private String client;
private String someproperty;
// default constructor
// parameterized constructor
// get set methods
}
public static List<Client> SetVM() {
List<Client> vm_list = new ArrayList<Client>();
// client codes example
Integer clientCodes[] = { 1, 2 };
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
// get the property values
for (Integer code : clientCodes) {
vm_list.add(new Client(prop.getProperty(code + "Client"), prop.getProperty(code + "someproperty")));
}
return vm_list;
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

Java eclipse error with exported runnable jar file

I have a problem with an exported jar file. When I run my project in Eclipse it runs fine, but when I run it as an exported jar from the console I receive the following error message:
java.io.FileNotFoundException: firstLaunch.properties (System can't find file)
or
java.io.FileNotFoundException: resources/config/firstLaunch.properties (System can't find file)
I tried to put it in to the resource folder and change syntax from firstLaunch.properties to /resource/config/firstLaunch.properties, but again it says the same thing but with a different path. I don't know why is this doing this.
Here is the code:
public void saveConfigFile(String file, String key, String value) {
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream(file);
// set the properties value
prop.setProperty(key, value);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
My syntax for executing the method is
if (properties.loadConfigFile("firstLaunch.properties", "value").equals(properties.loadConfigFile("true.properties", "true"))) {
properties.saveConfigFile("port.properties", "port", "8795");
properties.saveConfigFile("ip.properties", "ip", temp[1]);
properties.saveConfigFile("firstLaunch.properties", "value", "false");
settings.port = properties.loadConfigFile("port.properties", "port");
settings.myIp = properties.loadConfigFile("ip.properties", "ip");
} else {
settings.port = properties.loadConfigFile("port.properties", "port");
settings.myIp = properties.loadConfigFile("ip.properties", "ip");
}
Your problem probably has to do with how you are referencing the file location. Add some detail/code examples as to how you are referencing the code, so then we can be sure to help. Having said that here is another way to reference a properties file:
Put it in the classpath like this:
private static Properties prop = new Properties();
private static String filename = "<name of file>.properties";
InputStream input = <ClassName>.class.getClassLoader().getResourceAsStream(filename);
try {
if (input==null) {
loggerOut.log(Level.SEVERE, "Sorry, unable to find " + filename);
}
prop.load(input);
loggerOut.info("XML In storage path: " prop.getProperty("<property in file>"));
fileNameAndPath = prop.getProperty("fileNameAndPathIN").trim();
logNameAndPath = logPath + logName;
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input!=null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

save a created propertyfile in specific folder

How can I save a prop file in a specific folder for example,
now it is saved in the root I guess, but it needs to be in the same folder as the class where it is created.
I also want to know how to load it. If it possible to load a properties file easily from the root then it is okay as well to save it in the root.
code creating the file, first 2 lines with // ( = make code work now without using prop file), class name = Providers
public static DataAccessProvider createProvider (URL url) {
//MovieDAOOnline mdaoOn = new MovieDAOOnline();
//mdaoOn.setUrl(url);
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("config.properties");
// set the properties value
prop.setProperty("uri", url.toString());
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new OnlineProvider();
}
code for getting the file, first line in comment needs to be changed to get uri from propertie:
public Movie getMovie(int id) throws DataAccessException{
//StringBuilder builder = new StringBuilder(url.toString());
builder.append("movies.xml");
MovieConfigRead mcr = new MovieConfigRead();
List<Movie> film = null;
try {
film = mcr.geefMovies(builder.toString());
} catch (JAXBException e) {
throw new DataAccessException();
} catch (MalformedURLException e) {
throw new DataAccessException();
}
for (Movie movie : film) {
if (movie.getId() == id) {
return movie;
}
}
return null;
}

Unable to read properties file after creating it

I am creating a properties file and putting into my classpath folder Resources.
When I tried to read this file , i am not getting the expected result. i am getting the result of the previous values printed instead of the property values set now.
My class file is as follows :
public class App {
public static void main(String[] args) {
Properties prop = new Properties();
PrintWriter output = null;
try {
output = new PrintWriter("Resources/config.properties");
// set the properties value
prop.setProperty("database", "localhost");
prop.setProperty("dbuser", "mkyong");
prop.setProperty("dbpassword", "password");
// save properties to project root folder
prop.store(output, null);
if(output!=null) {
System.out.println("Output");
output.close();
}
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
output.close();
}
}
Properties prop1 = new Properties();
BufferedInputStream input = null;
try {
String filename = "config.properties";
input = (BufferedInputStream) AppCPLoad.class.getClassLoader().getResourceAsStream(filename);
if(input==null){
System.out.println("Sorry, unable to find " + filename);
return;
}
//load a properties file from class path, inside static method
prop1.load(input);
//get the property value and print it out
System.out.println(prop1.getProperty("database"));
System.out.println(prop1.getProperty("dbuser"));
System.out.println(prop1.getProperty("dbpassword"));
if(input!=null) {
System.out.println("Input");
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally{
if(input!=null){
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Please help.
When you run the program, the properties file is loaded and the values are read. After you rewrite the properties file, that doesn't mean that the properties you have loaded already have be to rewritten. You need to reload the properties file and re-read the values. You are looking for an implementation like ReloadableResourceBundleMessageSource

Categories