我有一个*分隔文件,包含白天日志文件中的计数。
我需要创建一个“全面计数”'使用这些数据的文件然而我无法弄明白。
我的文件布局如下:
01/11/2014*0123*0*3*0*1
01/11/2014*4567*1*1*2*4
02/11/2014*0123*1*2*1*0
02/11/2014*4567*5*3*2*1
这只是一个样本。但是,逻辑将是相同的...我需要将值相加并获得如下输出:
0123*1*5*1*1
4567*6*4*4*5
我目前正在使用BufferedReader迭代遍历文件:
while((strLine = br.readLine()) != null) ...
在包含每日数据的文件中,我感兴趣的代码(0123,4567)总是在同一位置,所以我可以将它们子字母串起来:
String code = strLine.subString(11, 15);
或拆分*:
上的一行String[] line = strLine.split("\\*");
String code = line[1];
但是这里是我被卡住的地方......我需要查看文件以查找'代码'并将其添加到计数中,实现此目的的最佳方法是什么?我尝试使用2D阵列,但无法完全了解它。
答案 0 :(得分:1)
Map<String, int[]> map = new HashMap<String, int[]>();
迭代文件时:
if (map.containsKey(key)) {
int[] arr = map.get(key);
//add values to array here
} else {
int[] newValues = parsedValues;//can use String.split('*'); here from the substring of the line
map.put(new String(key), newValues);
}
答案 1 :(得分:0)
我想我找到了一个有效的解决方案。它可能不是最优雅的,如果可以改进,请随时告诉我。
public int[][] total(String fileName) {
int[][] counts = null;
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String strLine;
Set<String> codeSet = new HashSet<String>();
while((strLine = br.readLine()) != null) {
codeSet.add(strLine.substring(11, 15));
}
String[] codes = codeSet.toArray(new String[codeSet.size()]);
Arrays.sort(codes);
counts = new int[codes.length][4];
br = new BufferedReader(new FileReader(fileName));
while((strLine = br.readLine()) != null) {
String[] line = strLine.split("\\*");
for(int i = 0; i < codes.length; i++) {
if(codes[i].equals(line[1])) {
for(int x = 0; x < 4; x++) {
counts[i][x] += Integer.parseInt(line[(x + 3)]);
}
}
}
}
br.close();
} catch(Exception e) {
e.printStackTrace();
}
return counts;
}