在iteye上看到的一道面试题  本人水货看不懂 不知道如何解决 希望有高人能够把代码大致写出来供学习问题如下现在有一个12G的日志XXX.log文件,里面存放用户登录记录格式如下: 
[用户名XXX:YYYY-mm-DD-HH-MM-ss:IP地址] 
问题1.找出活动用户(活动用户即登录次数最多)并且得到登录次数 
问题2.找出用户名为XXX的所有登录记录     前提: 
用java语言实现,且不得借三方工具框架包  不能放入数据库借助数据库的全文检索 
并且控制好CPU及内存的使用情况 

解决方案 »

  1.   

    好吧,刚看到讨论这个问题的帖子http://www.iteye.com/topic/1117670
      

  2.   

    我这个菜鸟对NIO完全没有概念  只求高人介绍 - -
      

  3.   

    没用过NIO的飘过只求拿分。。 String maxUserName = "";
    Integer maxLoginCount = 0;
    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(map.containsKey(userName))
    {
    map.put(userName, map.get(userName)+1);
    }
    else
    {
    map.put(userName, 1);
    }

    if(map.get(userName).intValue() > maxLoginCount.intValue())
    {
    maxUserName = userName;
    maxLoginCount = map.get(userName);
    }
    }
    br.close();
    fr.close();

    System.out.println(maxUserName + "登陆次数最多,为" + maxLoginCount);
      

  4.   


    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);
      

  5.   

    也不是很懂海量数据处理,下面的代码对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);  
      }
           }  
       }