一、读文件:
读取本地文件
BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(filename), "utf-8"));//设置编码格式为utf-8
String line=null;
while((line=reader.readLine())!=null){
System.out.println(line);
}
二、处理读到的line
1、将line按内部结构拆开:例如line内的字符是以逗号隔开的如:姓名,性别,年龄,选课
while ((line = reader.readLine()) != null) {
String[] rowData = line.split(",");// 每行以,分开
String name = rowData[0];
String sex = rowData[1];
String age = rowData[2];
String course=rowDate[3];
System.out.println(name+","+sex+","+age);
}
2、若学生选了多门课程,筛选出选择了多门课程的学生并记录选课数。这里用map
“姓名”作为map的键值,“选课”+“选课数”作为value
为value建一个类
public static class Value {// map的第二个参数,类
private String course;
private int n;
public Value(int n, String course) {
super();
this.course = course;
this.n = n;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
public String toString() {
return this.getN() + "," + this.getCarno();// n,course
}
}
3、用map来处理读取的文件内容
public static Map<String,Value> map = new HashMap<String, Value>();
...
while ((line = reader.readLine()) != null) {
String[] rowData = line.split(",");// 每行以,分开
String name = rowData[0];
String sex = rowData[1];
String age = rowData[2];
String course=rowDate[3];
if (map.containsKey(name)) {
Value info = map.get(name);// 如果存在该键值对应的键值map就取出来,取名字相同的
String path = info.getCourse();
int m = info.getN()
m = m + 1;
info.setN(m);
info.setCourse(course+","+path);//把课程加到一起
map.put(name,info)
} else {
Value info = new Value(1,course);
map.put(name, info);
}
}
这样就把相同姓名选了多门课程的信息提取在了map里面:<name → 课程数n,course>
4、再来处理map
循环遍历map
for (String str : map.keySet()) {
System.out.println("key = " +str+ " and value = " + map.get(str));
}