Hopefully someone is able to help, I'm relatively new at java and trying to work out how to use the properties function to read multiple property values, not necessarily in order or the full list and then put them into either an array or a string so that I can then pass to another class to do "stuff" like write to a file. There could potentially be hundreds of property values and only wanted to pick the ones I wanted.
I'm able to get one like properties.getProperty("ip"); and assign to a string but having issues with multiple as per below...
Any help would be greatly appreciated.
Properties properties = new Properties();
try {
properties.load(new FileInputStream(args[0]));
}
catch (IOException e) {
System.out.println("Error - IOException - File not found...");
}
String model = properties.getProperty("model");
String codeLevel = properties.getProperty("codeLvl");
String[] dmdCommand = new String[properties.getProperty("ip")
+ properties.getProperty("rangeS")
+ properties.getProperty("rangeL")
+ properties.getProperty("PhyPG")
+ properties.getProperty("PhyLDEV")
+ properties.getProperty("PhyProc")
+ properties.getProperty("PhyExG")
+ properties.getProperty("PhyExLDEV")
+ properties.getProperty("PhyCMPK")];
If you need additional info or data samples happy to supply.
Cheers and thanks in advance :)
If you know the "keys" to the properties, you can use an ArrayList of strings to store the properties.
for example:
List<String> propertyList = new ArrayList<String>();
propertyList.add(properties.getProperty("rangeS"));
Here I'm assuming that you do not know how many keys are you going to pick up from the properties and hence the suggestion to use an ArrayList, but if you do know the number of keys to be picked, you should definitely use an array of strings.
for example:
String[] propertyArray = new String[limit];
for(int i=0;i<limit;i++){
propertyArray[i]= new String(properties.getProperty(myKey));
}
here, "myKey" can be coded to change dynamically.
Related
I have searched for this on stackoverflow and found unrelated threads for this case. I have also tried on my own, and will keep trying until the solution. But it will be good if someone shows me if i am doing any mistakes in code.
I am having a HashSet so that i can keep away duplicate strings from being getting added to it. And if HashSet is adding then it must be a unique string.
My class declarations are :
public List<String> ContactsList;
public List<String> ContactsNumbersList;
My code to fetch contacts and adding it into these two lists by taking help of HashSet so that i keep duplicate numbers away is :
ContactsList = new ArrayList<String>();
ContactsNumbersList = new ArrayList<String>();
HashSet<String> normalizedNumbersAlreadyFound = new HashSet<>();
// Contacts Database queries
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[] {ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER}, null, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY +" ASC");
while (cursor.moveToNext())
{
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (normalizedNumbersAlreadyFound.add(phoneNumber))
{
phoneNumber = phoneNumber.replace("-","");
phoneNumber = phoneNumber.replace(" ","");
phoneNumber = phoneNumber.replace("(","");
phoneNumber = phoneNumber.replace(")","");
ContactsList.add(name);
ContactsNumbersList.add(phoneNumber);
}
}
cursor.close();
Well then why my ContactsNumbersList having duplicate entries...? Thanking you in advance for any suggestions.. which will help me.
There seems to be a problem with your design.
First and foremost, you don't need Lists if your goal is to use a collection without duplicates.
Just use your Set instead.
Secondly, and specifically to your code, you are checking whether the element is added to your Set before normalizing it and adding the normalized String to the List.
Therefore, it may very well be that your List will contain duplicates because two elements that differ before normalization may be equal after normalization.
This leads me back to advise you to use your Set directly and disregard using a List in this use case.
Example
List<String> source = Arrays.asList("123-456789", "(1)23456789");
System.out.printf("Source List contains: %s%n", source);
Set<String> set = new HashSet<>();
List<String> unnecessary = new ArrayList<>();
Set<String> useful = new HashSet<>();
for (String s: source) {
if (set.add(s)) System.out.printf("Added %s to set.%n", s);
s = s.replaceAll("[()-]", "");
System.out.printf("\t... now normalized to %s%n", s);
// s is now normalized
unnecessary.add(s);
useful.add(s);
}
System.out.printf(
"Set contains %s.%nUnnecessary List contains %s.%nUseful Set contains %s.%n",
set,
unnecessary,
useful
);
Output
Source List contains: [123-456789, (1)23456789]
Added 123-456789 to set.
... now normalized to 123456789
Added (1)23456789 to set.
... now normalized to 123456789
Set contains [(1)23456789, 123-456789].
Unnecessary List contains [123456789, 123456789].
Useful Set contains [123456789].
I have a problem which requires me to create an array that will store the name of a file, and then its contents. I tried to use this, to create an Array ArrayList<String, String> fileContent = new ArrayList<String, String>(); but it calls an error, that there are an incorrect number of arguments. Whats the best way to get around this problem?
Would it be better to make two Arrays, one that stores the names, and one that stores the data in the file. Or is there another inbuilt thing inside of java that would be better to use?
create a custom class
class MyClass{
String filename;
String content;
}
// use methods as you want
then use array list for MyClass
ArrayList<MyClass> fileContent = new ArrayList<MyClass>();
If you are going to increase the properties you want to store, the answer by #while true is the correct one. If you want to store the name and the file only, you can create a HashMap like this.
HashMap<String, File> myMap = new HashMap<String, File>();
And insert elements like this:
myMap.put("filename",myFile);
Hope it helps.
Create a class that stores what you want, like this:
class Contents {
String fileName;
ArrayList<String> fileContent;
public Contents(String fileName){
this.fileName = fileName;
fileContent = new ArrayList<String>;
}
//Any Methods you need
}
and create an ArrayList like this:
ArrayList<Contents> = new ArrayList<Contents>;
This way you can store the fileName and it's contents.
The error you get is because an ArrayList can only contain one class, like String or in this example Contents.
I am trying to get some values from config file. I have lot of keys and want to get only certain values. These values have keys starting with same initial name with a slight variation towards the end.
can Someone help me quickly?
assuming when you say key you mean value (as in values in an array),
final String PREFIX = "yourPrefix";
for(String value : valueList) {
if(value.startwith(PREFIX)) {
<do whatever...>
}
here is the link to the java Doc
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#startsWith(java.lang.String)
I am assuming you are scanning the config file for Strings that have similar prefixes. Why not try scanning them in grouped instead of scanning them in all in one hashmap. If you know already the specified prefixes try creating an arraylist for each prefix and while scanning receive the given prefix and add it accordingly.
StringTokenizer s = new StringTokenizer ("Configuration File : Server_intenties = keyId_11503, keyId_11903 : Server_passcodes = keyCode_1678, keyCode_9893", " ");
ArrayList<String> keyCode = new ArrayList();
ArrayList<String> keyId = new ArrayList();
while(s.hasMoreTokens){
String key = s.nextToken
if(key.contains("keyId")){
keyId.add(key);
}
if(key.contains("keyCode")){
keyCode.add(key);
}
}
System.out.println(keyCode);
System.out.println(keyId);
I created a HashMap to store a text file with the columns of information. I compared the key to a specific name and stored the values of the HashMap into an ArrayList. When I try to println my ArrayList, it only outputs the last value and leaves out all the other values that match that key.
This isn't my entire code just my two loops that read in the text file, stores into the HashMap and then into the ArrayList. I know it has something to do with my loops.
Did some editing and got it to output, but all my values are displayed multiple times.
My output looks like this.
North America:
[ Anguilla, Anguilla, Antigua and Barbuda, Antigua and Barbuda, Antigua and Barbuda, Aruba, Aruba, Aruba,
HashMap<String, String> both = new HashMap<String, String>();
ArrayList<String> sort = new ArrayList<String>();
//ArrayList<String> sort2 = new ArrayList<String>();
// We need a try catch block so we can handle any potential IO errors
try {
try {
inputStream = new BufferedReader(new FileReader(filePath));
String lineContent = null;
// Loop will iterate over each line within the file.
// It will stop when no new lines are found.
while ((lineContent = inputStream.readLine()) != null) {
String column[]= lineContent.split(",");
both.put(column[0], column[1]);
Set set = both.entrySet();
//Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
if(me.getKey().equals("North America"))
{
String value= (String) me.getValue();
sort.add(value);
}
}
}
System.out.println("North America:");
System.out.println(sort);
System.out.println("\n");
}
Map keys need to be unique. Your code is working according to spec.
if you need to have many values for a key, you may use
Map<key,List<T>>
here T is String (not only list you can use any collection)
Some things seems wrong with your code :
you are iterating on the Map EntrySet to get just one value (you could just use the following code :
if (both.containsKey("North America"))
sort.add(both.get("North America"));
it seems that you can have "North America" more than one time in your input file, but you are storing it in a Map, so each time you store a new value for "North America" in your Map, it will overwrite the current value
I don't know what the type of sort is, but what is printed by System.out.print(sort); is dependent of the toString() implementation of this type, and the fact that you use print() instead of println() may also create problems depending on how you run your program (some shells may not print the last value for instance).
If you want more help, you may want to provide us with the following things :
sample of the input file
declaration of sort
sample of output
what you want to obtain.
It seems that java.util.Properties assumes one value per propery key. That is,
foo=1
foo=2
is not expected,
Is there a class for this kind of multi-value property sheet, which also provides the load method?
Try:
foo=1,2
String[] foos = properties.getProperty("foo").split(",");
The java.util.Properties function is pretty limited. If you want support list, you might want try PropertyConfiguration from Apache Commons Configuration,
http://commons.apache.org/configuration/userguide/howto_properties.html#Using_PropertiesConfiguration
With it, you can set any delimiters to your list and it will split for you automatically. You can also do other fancy things in properties file. For example,
foo=item1, item2
bar=${foo}, item3
number=123
You can retrieve it like this,
Configuration config = new PropertiesConfiguration("your.properties");
String[] items = config.getStringArray("bar"); // return {"item1", "item2", "item3"}
int number = config.getInt("number", 456); // 456 is default value
Correct answer by Nick.
Or, if you can give a different subname to each value, you could have your properties be:
my.properties
foo.title=Foo
foo.description=This a big fat foo.
This won't provide the load method but a place to store them you could use a apache commons multivaluemap:
"A MultiValueMap decorates another map, allowing it to have more than one value for a key. "
This is often a requirement for http request parameters...
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/MultiValueMap.html
If you have a more complex example you might use the following:
# pairs of properties
source1=foo
target1=bar
source2=anotherFoo
target2=regardingBar
source3= ...
In your code you will have to search:
Map<String, String> myMap = new HashMap<>();
for (int i=1; i<max; i++) {
String source = properties.get("source" + i);
String target = properties.get("target" + i);
if (source == null || target == null) {
break;
}
myMap.put(source, target);
}
Drawback: updating the properties file. If you remove values *2, all the following values will not be added. To improve you might want to replace the break with a continue and stick to a maximum of allowed pairs.