Last active
August 29, 2015 14:16
-
-
Save Canop/92771faad6b7f55b3c1f to your computer and use it in GitHub Desktop.
CSV Parsing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.keods.gamaster; | |
import java.io.IOException; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.util.*; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
import java.util.stream.Stream; | |
/** | |
* Set of product targets | |
* Created by dys on 02/03/15. | |
*/ | |
public class PTSet { | |
private List<ProductTarget> productTargets = new ArrayList<>(); | |
private enum CsvValueType { | |
min, max | |
} | |
public static PTSet readFromCsvFile(Path path) throws IOException { | |
class CsvColDescriptor{ | |
String elemName; | |
CsvValueType type; | |
CsvColDescriptor(String elemName, CsvValueType type) { | |
this.elemName = elemName; | |
this.type = type; | |
} | |
void read(String s, ProductTarget pt){ | |
ElementTarget et = pt.getNotNullElementTarget(elemName); | |
try { | |
switch (type) { | |
case min: et.min = Float.parseFloat(s); break; | |
case max: et.max = Float.parseFloat(s); break; | |
} | |
} catch (NumberFormatException e) {/* nothing to do here*/} | |
} | |
} | |
try (Stream<String[]> lineStream = Files.lines(path).map(s -> s.split(";"))) { | |
PTSet ptSet = new PTSet(); | |
CsvColDescriptor[] colDescriptors; | |
Iterator<String[]> lines = lineStream.iterator(); | |
Pattern eMinMaxPattern = Pattern.compile("(?i)^(\\w+)\\s+(min|max)"); | |
colDescriptors = Arrays.stream(lines.next()).map(name -> { | |
Matcher matcher = eMinMaxPattern.matcher(name); | |
if (!matcher.find()) return null; | |
return new CsvColDescriptor( | |
matcher.group(1), | |
CsvValueType.valueOf(matcher.group(2).toLowerCase()) | |
); | |
}).toArray(CsvColDescriptor[]::new); | |
lines.forEachRemaining(line -> { | |
ProductTarget pt = new ProductTarget(); | |
pt.num = Integer.parseInt(line[0]); | |
for (int i = 1; i < line.length && i<colDescriptors.length; i++) { | |
if(colDescriptors[i]!=null) colDescriptors[i].read(line[i], pt); | |
} | |
ptSet.productTargets.add(pt); | |
}); | |
System.out.format("%d lines in set\n", ptSet.productTargets.size()); | |
return ptSet; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment