IO/NIO 例子

题目:

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

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

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

   要求用IO/NIO实现


思路如下:

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

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

  (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> 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> read(String fileName) throws IOException {
        HashMap> 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 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> read(String fileName) throws IOException {
        HashMap> 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 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 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> map;

    @Override
    public Result loginNum(String fileName) throws IOException {
        map = commFao.read(fileName);
        Set>> entrySet = map.entrySet();
        int num = Integer.MIN_VALUE;
        String name = null;
        for (Entry> entry : entrySet) {
            if (entry.getValue().size() > num) {
                num = entry.getValue().size();
                name = entry.getKey();
            }
        }
        return new Result(name, num);
    }

    @Override
    public List 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 list = service.loginRecord(fileName, "wangfan");
        System.out.println("登录者wangfan的详细信息为:");
        for (Passport passport : list) {
            System.out
                .println("登录名:" + passport.getName() + ",登录时间:" + passport.getTime() + "登录IP:" + passport.getIp());
        }
    }
}

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

wangfan	123456754	1.2.3.4
wangfan1	133456754	2.2.3.4
wangfan2	123446754	1.5.3.4
wangfan3	127456754	1.7.3.4
wangfan4	128456754	1.8.3.4
wangfan5	123456754	3.2.3.4
wangfan6	123456754	5.2.3.4
wangfan7	123456754	6.2.3.4
wangfan8	123456754	7.2.3.4
wangfan9	123456754	1.2.3.5
wangfan	123456756	1.2.3.4
wangfan	123756754	1.8.3.4
wangfan	129456754	1.9.3.4
wangfan	183456754	1.2.9.4
wangfan	193456754	1.2.6.4

运行效果:

IO/NIO 例子_第1张图片


你可能感兴趣的:(java)