Reputation: 241
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
}
}
}
}
Upvotes: 2
Views: 6644
Reputation: 38734
Here a one-liner that does what you want:
new File(/C:\Users\.............\input.txt/).readLines().collectEntries { it.trim().split(/\s*=\s*/) as List }
Upvotes: 0
Reputation: 1646
Try with this code:
def map =[:]
new File("file.txt").eachLine{line->
if(line.contains('=')&& (!line.startsWith("#"))){
map[line.split('=')[0]]=line.split('=')[1]
}
}
println map
Upvotes: 1
Reputation: 14621
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
Upvotes: 4