When I read the text file using Java, how can I skip first three rows of the text file?
Current program,
public class Reader {
public static void main(String[] args) {
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream("sample.txt")));
Map<String, Integer> result = new LinkedHashMap<String, Integer>();
Map<String, Integer> result2 = new LinkedHashMap<String, Integer>();
while (reader.ready()) {
String line = reader.readLine();
//split a line with spaces
String[] values = line.split("\s+");
//set a key date\tanimal
String key = values[0] + "\t" + values[1];
int sum = 0;
int count = 0;
//get a last counter and sum
if (result.containsKey(key)) {
sum = result.get(key);
count = result2.get(key);
} else{
}
//increment sum a count and save in the map with key
result.put(key, sum + Integer.parseInt(values[2]));
result2.put(key, count + 1);
}
//interate and print new output
for (String key : result.keySet()) {
Integer sum = result.get(key);
Integer count = result2.get(key);
System.out.println(key + " " + sum + "\t" + count);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Why can’t you just do this?
You can simplify the code and make it more readable by introducing these two classes. Then you can only maintain 1 Map,