之前没有注意过,现在复习一遍i/o
文件如下
1,张三,28
2,里斯,24
3,里斯,24
4,收到,42
5,收到,42
6,王五,42
7,赵六,24
读取文件一般分为字节流和字符流,java I/O就分为两大类
分别是 InputStream/OutputStream Reader/Writer
字节流
1 文件读写 FileInputStream/FileOutputStream
2 内存读写 ByteArrayInputStream/ByteArrayOutputStream
3 控制台读写 Scanner/BufferedReader
4 对象读写 ObjectInputStream/ObjectOutputStream
5 piped 管道 PipedInputStream/PipedOutputStream
字符流
Reader->FileReader->BufferedReader
字符流
字节流转化成字符流
InputStreamReader / OutputStreamReader
字节一般可以完成拷贝的任务
如果涉及到处理文本,就用字符流
下面代码实现按行读取(BufferedReader),获取上面的数据
public class TestGetNameSort {
public void getSrc() throws IOException{
InputStream is=TestGetNameSort.class.getResourceAsStream("a.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(is));
Map<String, Integer> map = new HashMap<String, Integer>();
String buf;
while((buf = in.readLine())!=null){
String[] str = buf.split(",");
if(str.length==3){
Integer value = map.get(str[1]);
if(value == null)
value=0;
map.put(str[1], value+1);
}
}
is.close();
in.close();
TreeSet<Person> ts = new TreeSet<Person>(new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
Person p1 = (Person)o1;
Person p2 = (Person)o2;
if(p1.getTimes()>p2.getTimes())
return 1;
if(p1.getTimes()<p2.getTimes())
return -1;
else
return p1.getName().compareTo(p2.getName());
}
});
Set<Entry<String,Integer>> entrySet = map.entrySet();
for (Entry<String, Integer> entry : entrySet) {
String name=entry.getKey();
int times =entry.getValue();
Person p = new Person(name,times);
ts.add(p);
}
for (Iterator<Person> iterator = ts.iterator(); iterator.hasNext();) {
Person object = (Person) iterator.next();
if(object.getTimes()>1)
System.out.println(object.getName()+" "+object.getTimes());
}
}
public static void main(String[] args) throws IOException {
TestGetNameSort tst = new TestGetNameSort();
tst.getSrc();
}
}