IO/NIO 例子

来源:互联网 发布:淘宝怎么买weed叶子 编辑:程序博客网 时间:2024/05/16 10:12

题目:

     passport日志由以下三个字段组成,用户名、访问时间、访问者的IP地址。 要求在passport日志中进行以下操作:

    1、找到访问次数最多的用户名,并求出访问次数

    2、找到指定用户的访问记录

   要求用IO/NIO实现


思路如下:

  (1)首先将文件读进来,一行一行的处理

  (2)对每一行,将姓名作为key,访问的记录对象作为value存入HashMap<String,List<访问的记录对象>>

  (3)在这个HashMap中做操作即可


代码如下:

封装的访问详情对象:

public class Passport {    private String name;    private Long time;    private String ip;    public Passport(String name, Long time, String ip) {        this.name = name;        this.time = time;        this.ip = ip;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Long getTime() {        return time;    }    public void setTime(Long time) {        this.time = time;    }    public String getIp() {        return ip;    }    public void setIp(String ip) {        this.ip = ip;    }}


IO访问接口:

import java.io.IOException;import java.util.HashMap;import java.util.List;public interface CommonFAO {    // 读文件,返回一个key为name,value为Passport对象的HashMap    public HashMap<String, List<Passport>> read(String fileName) throws IOException;}


BIO的实现:

import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;public class BIOFAOImpl implements CommonFAO {    @Override    public HashMap<String, List<Passport>> read(String fileName) throws IOException {        HashMap<String, List<Passport>> map = new HashMap<>();        BufferedReader br = new BufferedReader(new FileReader(fileName));        String str;        while ((str = br.readLine()) != null) {            String[] words = str.split("\t");            Passport pp = new Passport(words[0], Long.parseLong(words[1]), words[2]);            if (map.containsKey(words[0])) {                map.get(words[0]).add(pp);            } else {                List<Passport> list = new ArrayList<>();                list.add(pp);                map.put(words[0], list);            }        }        return map;    }}

NIO的实现:

import java.io.IOException;import java.io.RandomAccessFile;import java.nio.ByteBuffer;import java.util.ArrayList;import java.util.HashMap;import java.util.List;public class NIOFAOImpl implements CommonFAO {    @Override    public HashMap<String, List<Passport>> read(String fileName) throws IOException {        HashMap<String, List<Passport>> map = new HashMap<>();        RandomAccessFile aFile = new RandomAccessFile(fileName, "rw");        java.nio.channels.FileChannel inChannel = aFile.getChannel();        // 根据FileChannel的大小创建缓冲区        ByteBuffer buf = ByteBuffer.allocate((int) inChannel.size());        // 写到缓冲区        inChannel.read(buf);        // 切换缓冲区模式为读模式        buf.flip();        byte[] content = new byte[(int) inChannel.size()];        // 将缓冲区内的内容读到byte[]数组        buf.get(content, 0, (int) inChannel.size());        // 将byte数组转为String        String str = new String(content);        // 切分为一行一行的句子        String[] lines = str.split("\n");        // 遍历一行一行的句子,逐个处理并扔到HashMap        for (String line : lines) {            String[] words = line.split("\t");            Passport pp = new Passport(words[0], Long.parseLong(words[1]), words[2]);            if (map.containsKey(words[0])) {                map.get(words[0]).add(pp);            } else {                List<Passport> list = new ArrayList<>();                list.add(pp);                map.put(words[0], list);            }        }        aFile.close();        return map;    }}

service接口:

import java.io.IOException;import java.util.List;public interface Service {    // 找出登陆次数最多的用户名字name,并返回登陆次数    public Result loginNum(String fileName) throws IOException;    // 找出某个用户所有的登录记录    public List<Passport> loginRecord(String fileName, String name) throws IOException;}

service的实现

import java.io.IOException;import java.util.HashMap;import java.util.List;import java.util.Map.Entry;import java.util.Set;public class ServiceImpl implements Service {    private CommonFAO commFao = new BIOFAOImpl();// new NIOFAOImpl()    HashMap<String, List<Passport>> map;    @Override    public Result loginNum(String fileName) throws IOException {        map = commFao.read(fileName);        Set<Entry<String, List<Passport>>> entrySet = map.entrySet();        int num = Integer.MIN_VALUE;        String name = null;        for (Entry<String, List<Passport>> entry : entrySet) {            if (entry.getValue().size() > num) {                num = entry.getValue().size();                name = entry.getKey();            }        }        return new Result(name, num);    }    @Override    public List<Passport> loginRecord(String fileName, String name) throws IOException {        map = commFao.read(fileName);        return map.get(name);    }}

返回值对象包含次数和用户名:

public class Result {    private String name;    private int num;    public Result(String name, int num) {        this.name = name;        this.num = num;    }        public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getNum() {        return num;    }    public void setNum(int num) {        this.num = num;    }}

入口函数:

import java.io.IOException;import java.util.List;public class PasspartTest {    public static void main(String[] args) throws IOException {        Service service = new ServiceImpl();        String fileName = "/Users/bjhl/passport.log";        Result result = service.loginNum(fileName);        System.out.println("最多登录者是: " + result.getName() + ",登陆次数为" + result.getNum() + "次");        List<Passport> list = service.loginRecord(fileName, "wangfan");        System.out.println("登录者wangfan的详细信息为:");        for (Passport passport : list) {            System.out                .println("登录名:" + passport.getName() + ",登录时间:" + passport.getTime() + "登录IP:" + passport.getIp());        }    }}

测试文件内容:(制表符隔开)

wangfan1234567541.2.3.4wangfan11334567542.2.3.4wangfan21234467541.5.3.4wangfan31274567541.7.3.4wangfan41284567541.8.3.4wangfan51234567543.2.3.4wangfan61234567545.2.3.4wangfan71234567546.2.3.4wangfan81234567547.2.3.4wangfan91234567541.2.3.5wangfan1234567561.2.3.4wangfan1237567541.8.3.4wangfan1294567541.9.3.4wangfan1834567541.2.9.4wangfan1934567541.2.6.4

运行效果:



0 0
原创粉丝点击