Java.util.properties ? Using Config.getProperty
Hi all,
This one has been causing me a bit of a headache! I am using the Java.util.properties to create a file which looks like this:
#Tue Sep 13 19:15:06 GMT+02:00 2002
User=tristan
Password=bristol
Name=Tristan\ Webb
Rights=Tristan\ Webb
#Tue Sep 13 19:15:35 GMT+02:00 2002
User=adam
Password=newcastle
Name=Adam\ Jones
Rights=Adam\ Jones
The problem comes when I try to read the information back and put it in a Vector. Using the code below, it only ever puts the last users details (i.e. adam, Newcastle etc..) into the file and skips the first one. I have tried adding more users details, but it only ever reads the last entry. Is there anyway of forcing the config.getProperty to read the first entry in the file and then all the subsequesnt user details ?? I am thinking there must be a way of looping through the file, but im not sure where to start and am quite lost!
Many Thanks,
Properties config;
FileInputStream file;
file = new FileInputStream("password.cfg");
config = new Properties();
config.load(file);
User2 = config.getProperty("User");
Password = config.getProperty("Password");
name = config.getProperty("Name");
rights = config.getProperty("Rights");
UserDetails user = new UserDetails(User2, Password, name, rights);
userDetails.add(user);
The java.util.Properties class works like a dictionary: it stores values, which you can access using the keys.
The keys must be unique. In your case, the keys are not unique. If you do: String s = config.getProperty("User"); then how do you expect to get two values back (tristan and adam)?
You must make the keys unique in some way. For example, write your properties file like this:
#Tue Sep 13 19:15:06 GMT+02:00 2002
User.1=tristan
Password=.1bristol
Name.1=Tristan\ Webb
Rights.1=Tristan\ Webb
#Tue Sep 13 19:15:35 GMT+02:00 2002
User.2=adam
Password.2=newcastle
Name.2=Adam\ Jones
Rights.2=Adam\ Jones
Now use for example: String s = config.getProperty("User.1"); to get the name of the first user, etc.
Jesper
Similar Messages
-
Applet using java.util.Properties.setPropterty()
Hi,
I'm trying to use the java.util.Properties class in an Applet. More specifically the setProperty(String, String) method. My applet compiles fine but it crashes when I run it with IE (ver. 6). It shows an "NoSuchMethodError: method setProperty(Ljava.lang.String,Ljava.lang.String)". When I compile with javac, it doesn't complain but I guess the IE VM doesn't see that method. But Properties is part of java.util.*, so shouldn't IE have access to that class?
Any help is much appreciated?
Thanks
HeatherThe API for that method includes this:
Since:
1.2
That means it's a Java 2 method. The JVM in Internet Explorer doesn't support Java 2 methods (unless you load a plugin that does). -
Retrofitting java.util.Properties
Hi all,
why was java.util.Properties in JDK 1.5 not retrofitted to implement java.util.Map<String,String>?
This would have been the "natural" way to take advantage of typesafety.
I'm sure this has something to do with backwards compatibility, but what exactly woud it break?
Thanksjava.util.Properties extends java.util.Hashtable
java.util.Properties : private java.util.HashtableWhat does that actually buy you though?
I mean its really the difference between:
class Properties {
final Hashtable m_contents = new Hashtable();
public String getProperty(String key) {
return (String) m_contents.get(key);
}vs.
class Properties private extends Hashtable {
public String getProperty(String key) {
return (String) super.get(key);
}Which is nice and all, but it strikes me as syntactic sugar more than anything else.
I don't disagree: Properties should never have extended Hashtable, it should have encapsulated a Hashtable. Also Stack should not extend Vector, Booleans should not have a public constructor, it would even have been nicer if people actually used the Dictionary interface occassionally in 1.0/1.1.
Its easy to say these things now with the benefit of 20-20 hindsight. -
Java.util.Properties methods load & store
Does java.util.Properties methods load & store produce & load platform independent code?
You mean that it is better to use loadFromXML(InputStream in) and storeToXML(OutputStream os, String comment) methods of this class in order to have platform independent code?
-
Invalid data returned when iterating a java.util.Properties
Hi all,
I'm having trouble iterating thru the values in a java.util.Properties object.
This problem only occurs when passing in a java.util.Properties object into the constructor of a java.util.Properties.
Here's some example code. (A picture is worth....)
<pre>
import java.util.Properties;
import java.util.Iterator;
public class PropertyTest {
public static void main(String[] args) {
Properties validProp = new Properties();
//add some data
validProp.put("key1", "key1Value");
validProp.put("key2", "key2Value");
validProp.put("key3", "key3Value");
System.out.println("This will iterate...");
dumpPropertyFile(validProp); //This will iterate correctly
Properties inValidProp = new Properties(validProp);
System.out.println("This doesn't iterate correctly");
dumpPropertyFile(inValidProp); //This will not iterate
public static void dumpPropertyFile(Properties prop) {
Iterator iter = prop.keySet().iterator();
while (iter.hasNext()) {
String key = (String)iter.next();
System.out.println(key + "=" + prop.getProperty(key));
</pre>
I have searched the bug database, but didn't find any open bugs related to this issue.
Could someone let me know if this is a existing bug or has this bug already been addressed.
My setup.
NT 4.0 / jdk1.3.1
Thanks,I found this works.
Iterator e = _props.keySet().iterator();
while(e.hasNext())
String str = (String)e.next();
System.out.println("key(" + str + ")=" + _props.getProperty(str));
but the display sequence is always in descending order ???
Anyone has a clue ?
Input :
catch#2 Prop catch#2
prop2 Properties.test.2
catch#6 Prop catch#6
catch#3 Prop catch#3
catch#5 Prop catch#5
catch#4 Prop catch#4
prop3 test Properties
prop4 test Properties4
prop1 Properties.test.1
catch#1 Prop catch#1
Output:
prop4=test Properties4<
prop3=test Properties<
prop2=Properties.test.2<
prop1=Properties.test.1<
catch#6=Prop catch#6<
catch#5=Prop catch#5<
catch#4=Prop catch#4<
catch#3=Prop catch#3<
catch#2=Prop catch#2<
catch#1=Prop catch#1< -
Unable to validate a java.util.Properties XML based File
I cannot for the life of me figure out what is wrong with this xml file, but it fails the validation of java.util.Properties and as such won't be parsed in. Help!
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties version="1.0">
<entry key="bottleneckServer.address"></entry>
<entry key="bottleneckServer.port">8206</entry>
<entry key="bottleneckServer.confirmDelay">10</entry>
<entry key="bottleneckServer.cleanupDelay">120</entry>
</properties>Thanks in advance!This xml file works perfectly.
Here is some test code:
Properties p = new Properties();
p.loadFromXML(getClass().getClassLoader().getResourceAsStream("someFilePath/someFileName.xml"));
assert "8206".equals(p.getProperty("bottleneckServer.port")) : "Property 'bottleneckServer.port' != 8206"; -
Finding the key according to string length in java.util.Properties
Finding the key according to string length in java.util.Properties.
I know only String length only.i need to retrieve the values from the java.util.properties.
we know that we need to give the key value in order to retrieve the datas.
but my problem is i will give the length of the key instead of giving the key value but i need to retrieve the datas according to the length of the key. -
Error in Parser.fx file "incompatible types found : java.util.Properties"
Hi,
In parser file "Parser.fx",
public-read def PROPERTIES_PARSER = StreamParser {
override public function parse(input : java.io.InputStream) : RecordSet {
var props = javafx.util.Properties {};
props.load(input);
input.close();
MemoryRecordSet {
records: [
MapRecord {
fields: props
due to under line portion an error is appearing:
"incompatible types
found : javafx.util.Properties
required: java.util.Map
fields: props".
Please suggest some solution.
Thanks in advance.
regards,
Choudhary Nafees Ahmed
Edited by: ChoudharyNafees on Jul 5, 2010 3:48 AMParser.fx
package org.netbeans.javafx.datasrc;
import javafx.data.pull.PullParser;
import javafx.data.pull.Event;
import org.netbeans.javafx.datasrc.MemoryRecordSet;
public-read def PROPERTIES_PARSER = StreamParser {
override public function parse(input : java.io.InputStream) : RecordSet {
var props =java.util.Properties{};
props.load(input);
input.close();
MemoryRecordSet {
records: [
MapRecord {
fields: props
public-read def LINE_PARSER_FIELD_LINE = ".line";
public-read def LINE_PARSER = StreamParser {
override public function parse(input : java.io.Reader) : RecordSet {
var line : String;
var result : Record [] = [];
line = readLine(input);
// BEWARE ("" == null) is true
while (line != null or "".equals(line)) {
var map = new java.util.HashMap();
map.put(LINE_PARSER_FIELD_LINE, line);
var record = MapRecord {
fields: map
insert record into result;
line = readLine(input);
MemoryRecordSet {
records: result
function readLine(in : java.io.Reader) : String {
var str = new java.lang.StringBuilder;
while (true) {
var c = in.read();
if (c == -1) {
return if (str.length() == 0) then null else str.toString();
} else if (c == 0x0D) {
c = in.read();
if (c == 0x0A or c == -1) {
return str.toString();
str.append(0x0D);
} else if (c == 0x0A) {
return str.toString();
str.append(c as Character);
str.toString()
public-read def JSON_PARSER = StreamParser {
function toSequence(list : java.util.List) : Record [] {
var result : Record [] = [];
var ii = list.iterator();
while (ii.hasNext()) {
var r = ii.next() as Record;
insert r into result;
result
override public function parse(input : java.io.InputStream) : RecordSet {
var topLevel : Object;
def parser = PullParser {
documentType: PullParser.JSON
input: input
var mapStack = new java.util.Stack();
var currentMap : java.util.Map;
var recordsStack = new java.util.Stack();
var currentRecords : java.util.List;
var lastEvent: Event;
onEvent: function(event: Event) {
if (event.type == PullParser.TEXT) {
currentMap.put(event.name, event.text)
} else if (event.type == PullParser.INTEGER) {
currentMap.put(event.name, event.integerValue)
} else if (event.type == PullParser.NULL) {
currentMap.put(event.name, null)
} else if (event.type == PullParser.START_ELEMENT) {
if (lastEvent.type == PullParser.START_ARRAY_ELEMENT) return;
var oldMap = currentMap;
var temp = new java.util.HashMap();
temp.put(new Object(), null);
currentMap = temp;
currentMap.clear();
mapStack.push(currentMap);
if (topLevel == null) topLevel = currentMap;
if (oldMap != null) {
var mr = MapRecord {
fields: currentMap
if (event.name == "" and lastEvent.type == PullParser.START_VALUE) {
oldMap.put(lastEvent.name, mr)
} else {
oldMap.put(event.name, mr)
} else if (event.type == PullParser.START_ARRAY_ELEMENT) {
var temp = new java.util.HashMap();
temp.put(new Object(), null);
currentMap = temp;
currentMap.clear();
mapStack.push(currentMap);
var mr = MapRecord {
fields: currentMap
currentRecords.add(mr);
} else if (event.type == PullParser.END_ELEMENT) {
mapStack.pop();
if (not mapStack.empty()) {
currentMap = mapStack.peek() as java.util.HashMap;
} else {
currentMap = null;
} else if (event.type == PullParser.END_ARRAY_ELEMENT) {
if (lastEvent.type == PullParser.END_ELEMENT) return;
mapStack.pop();
if (not mapStack.empty()) {
currentMap = mapStack.peek() as java.util.HashMap;
} else {
currentMap = null;
} else if (event.type == PullParser.START_ARRAY) {
currentRecords = new java.util.ArrayList();
recordsStack.push(currentRecords);
if (topLevel == null) topLevel = currentRecords;
} else if (event.type == PullParser.END_ARRAY) {
var set = MemoryRecordSet {
records: toSequence(currentRecords)
currentMap.put(event.name, set);
recordsStack.pop();
if (not recordsStack.empty()) {
currentRecords = recordsStack.peek() as java.util.List;
} else {
currentRecords = null;
lastEvent = event;
parser.parse();
if (topLevel instanceof java.util.Map) {
var mr = MapRecord {
fields: topLevel as java.util.Map
MemoryRecordSet {
records: [mr]
} else {
// List
var rs = MemoryRecordSet {
records: toSequence(topLevel as java.util.List)
rs
parser.parse();
var mr = MapRecord {
fields: topLevel as java.util.Map
MemoryRecordSet {
records: [mr] -
See Java System properties using WebLogic Server console
hi
If I deploy "systempropertiesweb.war" [1] on WebLogic Server I can see all or individual Java System properties,
e.g. http://localhost:7101/systempropertiesweb/systemproperties?property=java.version results in "java.version = 1.6.0_24"
Is it possible to see the same Java System properties using WebLogic Server Administration Console? If so, how?
( via http://localhost:7101/console )
- [1] at SystemPropertiesApp/SystemPropertiesWeb/deploy/systempropertiesweb.war
in http://www.consideringred.com/files/oracle/2013/SystemPropertiesApp-v0.01.zip
many thanks
Jan VerveckenThanks for your reply Timo.
Timo Hahn wrote:
I don't think that there is an option to see this in the admin console. ...Thanks for the confirmation.
... There my be a mbean but I did not find it.Well, if I start JConsole (e.g. at C:\oracle\jdevstudio111240-mw\jdk160_24\bin\jconsole.exe ) and connect to e.g. Local Process "weblogic.Server", on the MBeans tab I can navigate to java.lang:type=Runtime which has an SystemProperties attribute.
But, I don't know how to get to this same MBean using the WebLogic Server Administration Console (if possible).
regards
Jan Vervecken -
How is java.util.logging used to log to unix syslog?
I'm trying to log out to syslog using the java.util.logging that is now in 1.4. I've read all I can find on this topic (not much) and have solicited the used of some syslog free ware (protomatter) but still can't get this to work. I feel like I'm missing something simple here, any help would be appreciated....
Here is my latest attempt:
import java.util.logging.*;
import java.util.*;
import java.io.*;
import com.protomatter.syslog.SyslogHandler;
public class SyslogTest
public static void main(String argv[]){
Logger logger2 = Logger.getLogger("local3");
SyslogHandler ch = new SyslogHandler();
ch.setLevel(Level.WARNING);
logger2.addHandler(ch);
logger2.warning("this is a log message");
if (logger2.isLoggable(Level.WARNING)) {
System.out.println("Is LOGGABLE");
else {
System.out.println("Is not loggable");
When this is run nothing is printed to any of the local3 facilities. I've verified that syslog is running fine from the command line using unix logger, so the problem seems to be isolated to my java.
Thanks.Hi,
What is in your logging.properties file? Can you also include the contents of this file?
Cheers,
Craig. -
USage of import java.util.* & using another package
When we use import java.util.*; from where does JAVA take the class that are related to util, when I did search for "util" in my machine, I got about 50 results for folders named util and also some where in a folder called "java" when I opened it it did not have the classes, that I was expecting. So I am not clear where does it get the class files from. This is not only for this but for any import commands like import java.io.*;
When we get another package or source code which was written in java and want to use it in our code where do we have keep the files ? eg. i have the java code that i m writing in c:\java then do I put all the downloaded related files in that folder and then run the code ? or i keep a folder inside java folder and then import them into my code ?
please do advice.
Thanks in advance.When we use import java.util.*; from where does JAVA
take the class that are related to util,It means when you use a classname in your code, and that classname is neither in the same package as the class you're writing, nor imported specifically by classname, that it will search for it.
Where it searches is every folder called util whose parent folder is called java which in turn is at the root level of one of the classpath elements. That is, if classpath contains "A" and "B", and you refer to a class called "Foo", then it will look for "A/java/util/Foo.class" and "B/java/util/Foo.class".
search for "util" in my machine, I got about 50
results for folders named util and also some where in
a folder called "java" when I opened it it did not
have the classes, that I was expecting. So I am not
clear where does it get the class files from. This is
not only for this but for any import commands like
import java.io.*; All the java.* and javax.* and whatever else it part of the core API is in rt.jar, which lives inside the Java distribution. Classpath elements can be directories or jar files or zip files. -
Java.util.ResourceBundle VS java.util.Properties
I want to keep some key values pair outside program in a properties file and use that in my program. There is no requirement of localization. Should i use ResourceBundle or Properties class? Previously I have used Properties class for this purpose but in my current project ResourceBundle is being used. Is there any benefits in using ResourceBundle? will it be faster to read properties using ResourceBundle?
ResourceBundles support internationalization. If you know that don't need it and Properties suffice, okay then.
Forget about "fast", both will have to read from the disk (slow) and both will use hashmaps (fast look-up). And both will probably do it in the same way. -
Doubt in java.util.Properties
I have a configuration file which consists of name & value pairs. For editing this file i am using Properties class. The problem is , when it finds any property value which consists of character : (colon), its automatically inserting \ (backslash) before the colon(:). How can i get rid of this problem. Any help is highly appreciated. Thank you
Well, basically that's part of the formatdefinition
that Properties uses. If you don't do it, then you
aren't really using Properties format and you'llhave
to do your own IO.Thanks for the reply. Is there anyother api or class
that can be used to resolve my problem.What is the problem? A character is escaped, but you will get : when you read the value. You don't have a problem as long as all reading / writing is done through that class. -
Java.util.Properties.load() not loading all properties
Hi,
I'm trying to load the following properties into my Properties class. However, Im only able to load SOME properties not ALL (11 to be precise)
This is my properties file :
~~~~~~~~~~~~~~~~~~~~~
gds.host=chissd235.bankofamerica.com
gds.datasource=gds.310.fob1
its.dataSource=gds.310.fob1
adv.dataSource=adv.310.fob1
gds.port=9650
gds.dataType=FpML
maxNumberOfConnectors=1000
itsConnectionMethod=ejb
advDB.driverToUse=jConnect2
advDB.userName=advDev1User
advDB.password=advDev1User
advDB.databaseName=advDev1
advDB.serverName=chisdd30.bankofamerica.com
advDB.port=2910
its.user=derivuser
This is my java code snippet:
~~~~~~~~~~~~~~~~~~~~~~~
private void loadProperties()
try
GDSConfigurationAdapter adapter = new GDSConfigurationAdapter();
String configurationResource = adapter.getConfigurationPropertiesResource();
load(loadStream(configurationResource));
String eventingPropsResource = adapter.getEventingPropertiesResource();
load(loadStream(eventingPropsResource));
} catch (IOException e)
throw new RuntimeException("Could not load GDS/Eventing properties");
private InputStream loadStream(String propFile) throws IOException
InputStream propStream = ResourceLocator.getResourceAsStream(propFile);
if (propStream == null)
logger.warning("could not find in JAR! Looking in classpath: " + propFile);
propStream = ResourceLocator.getResourceAsStream(propFile);
if (propStream == null)
IOException t = new IOException("Failed to load property file: " + propFile);
logger.throwing(getClass().getName(), "loadProperties", t);
throw t;
return propStream;
Any help will be appreciated.
Thanks
BjorkHi,
I'm trying to load the following properties into my Properties class. However, Im only able to load SOME properties not ALL (11 to be precise)
This is my properties file :
~~~~~~~~~~~~~~~~~~~~~
gds.host=chissd235.bankofamerica.com
gds.datasource=gds.310.fob1
its.dataSource=gds.310.fob1
adv.dataSource=adv.310.fob1
gds.port=9650
gds.dataType=FpML
maxNumberOfConnectors=1000
itsConnectionMethod=ejb
advDB.driverToUse=jConnect2
advDB.userName=advDev1User
advDB.password=advDev1User
advDB.databaseName=advDev1
advDB.serverName=chisdd30.bankofamerica.com
advDB.port=2910
its.user=derivuser
This is my java code snippet:
~~~~~~~~~~~~~~~~~~~~~~~
private void loadProperties()
try
GDSConfigurationAdapter adapter = new GDSConfigurationAdapter();
String configurationResource = adapter.getConfigurationPropertiesResource();
load(loadStream(configurationResource));
String eventingPropsResource = adapter.getEventingPropertiesResource();
load(loadStream(eventingPropsResource));
} catch (IOException e)
throw new RuntimeException("Could not load GDS/Eventing properties");
private InputStream loadStream(String propFile) throws IOException
InputStream propStream = ResourceLocator.getResourceAsStream(propFile);
if (propStream == null)
logger.warning("could not find in JAR! Looking in classpath: " + propFile);
propStream = ResourceLocator.getResourceAsStream(propFile);
if (propStream == null)
IOException t = new IOException("Failed to load property file: " + propFile);
logger.throwing(getClass().getName(), "loadProperties", t);
throw t;
return propStream;
Any help will be appreciated.
Thanks
Bjork -
Java.util.Properties
I execute this piece of code on application startup
public final Properties loadProperties() throws VmsBaseException {
Properties prop = new Properties();
prop.setProperty("ei.properties.file.import.path", "C:/projects/folders/input");
prop.setProperty("ei.properties.file.output.path", "C:/projects/folders/output");
prop.setProperty("ei.properties.file.name.pattern", "*.xml");
prop.setProperty("ei.properties.fixed.delay", "6000");
prop.setProperty("ei.properties.file.poller.interval", "100");
prop.setProperty("ei.properties.file.archive.path", "C:/projects/folders/archiveFolder/");
prop.setProperty("ei.properties.file.error.path", "C:/projects/folders/errorFolder/");
return prop;
Later on I would like my other beans to get hold of this properties and use the value inside it.
Any Idea how to achieve itManjit wrote:
Later on I would like my other beans to get hold of this properties and use the value inside it.
Any Idea how to achieve itYes, put the properties object somewhere where you can always reach it. Either that or let any piece of code that needs it call your loadProperties() method.
I'm sorry but your question is very open ended, so it is nearly impossible to be more specific.
Maybe you are looking for
-
How to erase the content of a cube
Hello. How could I fully erase the data contained in a cube, preserving the outline? Note that I don't mean substituting values with zeros, for I need MISSING VALUES and not zeros. Thanks in advance.
-
Problem in installing subway surf
I have downloaded subway surfer from itunes to my pc. but when i tried to install that into my iPAD MINI, i get a message stating "subway surf failed to install". i tried for times, but i get same message. can u please help me in installing it????
-
Pass iView property as parameter to JSP in PAR file.
Hi All, I have a custom created PAR file in which there is a JSP page there is a variable which I need to provide to users as a configurable property of the iView. So that when a user configures a value to that defined property to the iView, my JSP f
-
Insert Personnal Number in Easy Cost Planning
Dear Expert, I make project cost sheet using easy cost planning. I want to input the personnal number and the person cost there. is it possible? if yes, how i do this? what item category should i choose? Thx
-
Photoshop Elements Organizer problems:
I have been using Elements 12 very successfully until today. When I opened the Organizer, I can only see the bottom half of the page. The Folders panel on the left of the screen and the Tags panel on the right of the screen are out of site and "off t