I have a properties file say as follows:
apple=1
mango=2
banana=3
pineapple=4
I am using value annotation in the java program to access the values. I have a method in my class that computes a value i want to update the apple attribute in the properties file with the value that the method returns.
public class test {
#Value("${apple}")
private int apple;
public void testMethod() {
int new_val = 0;
if (apple > 0)
new_val = 300;
else
new_val = 200;
// now i want to update the value of apple in the file to new_val,(apple = new_val) other attributes should remain unchanged.
}
}
can someone let me know how to update the value in the properties file. In this example i want my properties file to become
apple=300
mango=2
banana=3
pineapple=4
Usually we defines constant values in properties, so it does not change.
But if it is your requirement to change it.
You can do it like:
1) Using Apache Commons Configuration library
PropertiesConfiguration conf = new PropertiesConfiguration("yourproperty.properties");
props.setProperty("apple", "300");
conf.save();
2) Using Java input and output stream
FileInputStream in = new FileInputStream("yourproperty.properties");
Properties props = new Properties();
props.load(in);
in.close();
FileOutputStream out = new FileOutputStream("yourproperty.properties");
props.setProperty("apple", "300");
props.store(out, null);
out.close();
Related
I want to store the key values pair in java from the config.properties file. Problem is it has some other which in dont want to store in array or hashmap.Below is my config.properties file. One thing the line must start with #usergroup and end of line should be End_TT_Executive as described in the file
#Usergroup
TT_Executive
#Tilename
KPI
#No of Submenu=3
#Submenu_1
OPs_KPI=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Submenu_2
Ontime_OnBudget=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#submenu_3
Ops_KPI_Cloud=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Tilename
Alerting Dashboard
#No of submenu=0
Alerting_Dashboard=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Tilename
FTE_Dashboard
#No of submenu=3
#Submenu_1
FTE_Market_Sector_TT_Executive= https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#submenu_2
FTE_Account_TT_Executive= http://tntanalytics1.sl1430087.sl.dst.ibm.com/ibmcognos/bi/?pathRef=.public_folders%2FP=false
#Submenu_3
FTE_Laborpool_TT_Executive= https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Tilename
PCR
#No of Submenu=0
PCR=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
End_TT_Executive
How can I do this? The key value pair are with URL only rest is some title for understanding.
Suppose your config.properties is like:
p1=abc
p2=def
p3=zxc
p4=eva
and you want to load p1 and p2 to map.
You can load all properties into Properties instance with:
InputStream inputStream = null;
try
{
inputStream = new BufferedInputStream(new FileInputStream("config.properties"));
Properties properties = new Properties();
properties.load(new InputStreamReader(inputStream, "UTF-8")); // load all properties in config.properties file
}
catch ( IOException e )
{
e.printStackTrace();
}
finally
{
inputStream.close();
}
Then you create a map:
Map<String, String> propertyMap = new HashMap<>();
You also need a String[] to store all properties which you want to load to propertyMap.
String[] wantedProperties = new String[]{"p1", "p2"};
Then you write a for loop to load the properties you wanted:
for (String property : wantedProperties) {
propertyMap.put(property, properties.getProperty(property));
}
Now propertyMap is what you want.
If you want to store to List:
List<String> propertyList = new ArrayList<>();
for (String property : wantedProperties) {
propertyList.add(properties.getProperty(property));
}
This is the way to save to list. It'll help you more if you find the solution yourself.
I'm trying to load properties to a Properties object in java using load(new FileReader()) method. All the properties are loaded except the properties start with(#) commented ones. How to load these commented properties to the Properties object using java API. Only manual way?
Thanks in Advance.
I could propose you to extend the java.util.Properties class to override this specificities but it was not designed for it : many things are hardcoded and not overridable. So you should do entire copy-paste of methods with little modification.
For example, at a time, the LineReader used in internal does that when you load a properties file :
if (isNewLine) {
isNewLine = false;
if (c == '#' || c == '!') {
isCommentLine = true;
continue;
}
}
The # is hardcoded.
Edit
Another way could be read line by line the proprties file, remove the first char if it is # and write the read line, modified if needed, in a ByteArrayOutputStream. then you could load the properties with a ByteArrayInputStream from ByteArrayOutputStream.toByteArray().
Here a possible implementation with a unit test :
With as input myProp.properties :
dog=woof
#cat=meow
The unit test :
#Test
public void loadAllPropsIncludingCommented() throws Exception {
// check properties commented not retrieved
Properties properties = new Properties();
properties.load(LoadCommentedProp.class.getResourceAsStream("/myProp.properties"));
Assert.assertEquals("woof", properties.get("dog"));
Assert.assertNull(properties.get("cat"));
// action
BufferedReader bufferedIs = new BufferedReader(new FileReader(LoadCommentedProp.class.getResource("/myProp.properties").getFile()));
ByteArrayOutputStream out = new ByteArrayOutputStream();
String currentLine = null;
while ((currentLine = bufferedIs.readLine()) != null) {
currentLine = currentLine.replaceFirst("^(#)+", "");
out.write((currentLine + "\n").getBytes());
}
bufferedIs.close();
out.close();
// assertion
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
properties = new Properties();
properties.load(in);
Assert.assertEquals("woof", properties.get("dog"));
Assert.assertEquals("meow", properties.get("cat"));
}
# Compulsory Dimension to create port
xOffset=-3
yOffset=50
How to get these xOffset and YOffset in java file.I tried with inputstream but not getting.These variable should get loaded in java file.
You can use Properties class from Java library
Properties prop = new Properties();
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(propFileName);
prop.load(inputStream);
The you can get the values as
prop.getProperty("propertyname");
Try the following code:
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("your_config.properties");
prop.load(input);
System.out.println(prop.getProperty("xOffset"));
System.out.println(prop.getProperty("yOffset"));
} catch (IOException e) {
// ...
}
As above explained Create a Function to read the property File During or Before Selenium Driver Constructor . So you can use them in test ( Help in Desire Capability Impl).
Store the values in Public Static final ( If you don not want to change them in Selenium and use as Default Property input)
As the values are read by Java Propertie file or .config file before selenium Driver so you can use them in Driver constructor or if you don't want you can use those properties stored as Static anywhere in the project. These values act as GLOBAL param.
Looked at lots of examples for this, and so far no luck. I'd like to classify free text.
Configure a text classifier. (FilteredClassifier using StringToWordVector and LibSVM)
Train the classifier (add in lots of documents, train on filtered text)
Serialize the FilteredClassifier to disk, quit the app
Then later
Load up the serialized FilteredClassifier
Classify stuff!
It goes ok up to when I try to read from disk and classify things. All the documents and examples show the training list and testing list being built at the same time, and in my case, I'm trying to build a testing list after the fact.
A FilteredClassifier alone is not enough to create a testing Instance with the same "dictionary" as the original training set, so how do I save everything I need to classify at a later date?
http://weka.wikispaces.com/Use+WEKA+in+your+Java+code just says "Instances loaded from somewhere" and doesn't say anything about using a similar dictionary.
ClassifierFramework cf = new WekaSVM();
if (!cf.isTrained()) {
train(cf); // Train, save to disk
cf = new WekaSVM(); // reloads from file
}
cf.test("this is a test");
Ends up throwing
java.lang.ArrayIndexOutOfBoundsException: 2
at weka.core.DenseInstance.value(DenseInstance.java:332)
at weka.filters.unsupervised.attribute.StringToWordVector.convertInstancewoDocNorm(StringToWordVector.java:1587)
at weka.filters.unsupervised.attribute.StringToWordVector.input(StringToWordVector.java:688)
at weka.classifiers.meta.FilteredClassifier.filterInstance(FilteredClassifier.java:465)
at weka.classifiers.meta.FilteredClassifier.distributionForInstance(FilteredClassifier.java:495)
at weka.classifiers.AbstractClassifier.classifyInstance(AbstractClassifier.java:70)
at ratchetclassify.lab.WekaSVM.test(WekaSVM.java:125)
Serialize your Instances which holds the definition of the trained data -similar dictionary?- while you are serializing your classifier:
Instances trainInstances = ... //
Instances trainHeader = new Instances(trainInstances, 0);
trainHeader.setClassIndex(trainInstances .classIndex());
OutputStream os = new FileOutputStream(fileName);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(os);
objectOutputStream.writeObject(classifier);
if (trainHeader != null)
objectOutputStream.writeObject(trainHeader);
objectOutputStream.flush();
objectOutputStream.close();
To desialize:
Classifier classifier = null;
Instances trainHeader = null;
InputStream is = new BufferedInputStream(new FileInputStream(fileName));
ObjectInputStream objectInputStream = new ObjectInputStream(is);
classifier = (Classifier) objectInputStream.readObject();
try { // see if we can load the header
trainHeader = (Instances) objectInputStream.readObject();
} catch (Exception e) {
}
objectInputStream.close();
Use trainHeader to create new Instance:
int numAttributes = trainHeader.numAttributes();
double[] vals = new double[numAttributes];
for (int i = 0; i < numAttributes - 1; i++) {
Attribute attribute = trainHeader.attribute(i);
//If your attribute is nominal or string:
double value = attribute.indexOfValue(myStrVal); //get myStrVal from your source
//If your attribute is numeric
double value = myNumericVal; //get myNumericVal from your source
vals[i] = value;
}
vals[numAttributes] = Instance.missingValue();
Instance instance = new Instance(1.0, vals);
instance.setDataset(trainHeader);
return instance;
I have some questions regarding reading and writing to CSV files (or if there is a simpler alternative).
Scenario:
I need to have a simple database of people and some basic information about them. I need to be able to add new entries and search through the file for entries. I also need to be able to find an entry and modify it (i.e change their name or fill in a currently empty field).
Now I'm not sure if a CSV reader/writer is the best route or not? I wouldn't know where to begin with SQL in Java but if anyone knows of a good resource for learning that, that would be great.
Currently I am using SuperCSV, I put together a test project based around some example code:
class ReadingObjects {
// private static UserBean userDB[] = new UserBean[2];
private static ArrayList<UserBean> arrUserDB = new ArrayList<UserBean>();
static final CellProcessor[] userProcessors = new CellProcessor[] {
new StrMinMax(5, 20),
new StrMinMax(8, 35),
new ParseDate("dd/MM/yyyy"),
new Optional(new ParseInt()),
null
};
public static void main(String[] args) throws Exception {
ICsvBeanReader inFile = new CsvBeanReader(new FileReader("foo.csv"), CsvPreference.EXCEL_PREFERENCE);
try {
final String[] header = inFile.getCSVHeader(true);
UserBean user;
int i = 0;
while( (user = inFile.read(UserBean.class, header, userProcessors)) != null) {
UserBean addMe = new UserBean(user.getUsername(), user.getPassword(), user.getTown(), user.getDate(), user.getZip());
arrUserDB.add(addMe);
i++;
}
} finally {
inFile.close();
}
for(UserBean currentUser:arrUserDB){
if (currentUser.getUsername().equals("Klaus")) {
System.out.println("Found Klaus! :D");
}
}
WritingMaps.add();
}
}
And a writer class:
class WritingMaps {
public static void add() throws Exception {
ICsvMapWriter writer = new CsvMapWriter(new FileWriter("foo.csv", true), CsvPreference.EXCEL_PREFERENCE);
try {
final String[] header = new String[] { "username", "password", "date", "zip", "town"};
String test = System.getProperty("line.seperator");
// set up some data to write
final HashMap<String, ? super Object> data1 = new HashMap<String, Object>();
data1.put(header[0], "Karlasa");
data1.put(header[1], "fdsfsdfsdfs");
data1.put(header[2], "17/01/2010");
data1.put(header[3], 1111);
data1.put(header[4], "New York");
System.out.println(data1);
// the actual writing
// writer.writeHeader(header);
writer.write(data1, header);
// writer.write(data2, header);
} finally {
writer.close();
}
}
}
Issues:
I'm struggling to get the writer to add a new line to the CSV file. Purely for human readability purposes, not such a big deal.
I'm not sure how I would add data to an existing record to modify it. (remove and add it again? Not sure how to do this).
Thanks.
Have you considered an embedded database like H2, HSQL or SQLite? They can all persist to the filesystem and you'll discover a more flexible datastore with less code.
The easiest solution is to read the file at application startup into an in-memory structure (list of UserBean, for example), to add, remove, modify beans in this in-memory structure, and to write the whole list of UserBean to the file when the app closes, or when the user chooses to Save.
Regarding newlines when writing, the javadoc seems to indicate that the writer will take care of that. Just call write for each of your user bean, and the writer will automatically insert newlines between each row.