日期:2014-05-20  浏览次数:20614 次

一道面试题,希望用NIO完成
在iteye上看到的一道面试题 本人水货看不懂 不知道如何解决 希望有高人能够把代码大致写出来供学习

问题如下



现在有一个12G的日志XXX.log文件,里面存放用户登录记录格式如下: 
[用户名XXX:YYYY-mm-DD-HH-MM-ss:IP地址] 


问题1.找出活动用户(活动用户即登录次数最多)并且得到登录次数 
问题2.找出用户名为XXX的所有登录记录  

前提: 
用java语言实现,且不得借三方工具框架包 不能放入数据库借助数据库的全文检索 
并且控制好CPU及内存的使用情况 




------解决方案--------------------
呵呵。。今天大家都在过光棍节啊。。没时间啊。。我先记下。。回去试试。。
------解决方案--------------------
海量数据处理专题(一)——开篇
------解决方案--------------------
Java code

        int count = 0;
        String who = "b";
        Map<String,Integer> map = new HashMap<String,Integer>();
        FileReader fr = new FileReader("e:\\a.log");
        BufferedReader br = new BufferedReader(fr);
        
        String str = null;
        while((str = br.readLine()) != null)
        {
            String userName = str.substring(4, str.indexOf(":")-str.indexOf("[用户名"));
            if(userName.equals(who))
            {
                count++;
            }
        }
        br.close();
        fr.close();
        
        System.out.println(who + "登陆次数为" + count);

------解决方案--------------------
也不是很懂海量数据处理,下面的代码对20G文件可能也无能为力:
public class FilterFile {
public static void main(String[] args) throws Exception {
String infile = "C:\\alluser.log";
String outfile = "C:\\xxx.log";
// 获取源文件和目标文件的输入输出流
FileInputStream fin = new FileInputStream(infile);
FileOutputStream fout = new FileOutputStream(outfile);
// 获取输入输出通道
FileChannel fcin = fin.getChannel();
FileChannel fcout = fout.getChannel();
// 创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
// clear方法重设缓冲区,使它可以接受读入的数据
buffer.clear();
// 从输入通道中将数据读到缓冲区
int r = fcin.read(buffer);
// read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1
if (r == -1) {
break;
}
// flip方法让缓冲区可以将新读入的数据写入另一个通道
buffer.flip();
// 从输出通道中将数据写入缓冲区
//如果包含用户信息则写入,否则不写入,可以优化一下看看能否精确到只写一行而不是整个buffer
if(buffer.toString().indexOf("xxx")){
fcout.write(buffer);
}
}
}