jane jane - 7 months ago 91
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
contains before equal and
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 ->

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