jane jane - 10 months ago 116
Groovy Question

create map in groovy

I have the below file :

name = David
city = sydney
COuntry = Australia


I am trying to create a hash map using groovy and split it at
=
and store it in an array such that
part[0]
contains before equal and
part[1]
contains after equal. I am then trying to create a map here .

Desired output :

def mapedData = [name :david , city : sydney , country :australia ]


My try :

String s=""
def myfile = new File("C:/Users/.............")
BufferedReader br = new BufferedReader(new FileReader(myfile));

Map<String, String> map = new HashMap<String, String>();
while((s = br.readLine()) != null) {
if(!s.startsWith("#")) {
StringTokenizer st=new StringTokenizer(s, "=")
while(st.hasMoreElements()) {
String line=st.nextElement().toString().trim()
print line
}
}
}
}

Answer Source

If you want to create a map from a file in Groovy, you can use java.util.Properties for that. Here is an example:

def file = new File("C:\\stackoverflow\\props.properties")
def props = new Properties()
file.withInputStream { stream ->
    props.load(stream)
}
println(props)

This prints out:

[key1:value1, key2:value2]

The props.properties file contains this:

# Stackoverflow test
key1 = value1
key2 = value2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download