最近做项目遇到一个问题,就是读一个日志文档,格式如下
[     afc][     7d0][       0] FileIoMapper Initialize successed![     afc][     7d0][       0] PortMapper Initialize successed![     afc][     7d0][       0] AppHookKernelObject Initialize successed[     afc][     7d0][       0] Api hooking successed![     afc][     7d0][       0] V3Hook.dll has been loaded[     afc][     7d0][       0] CreateProcessInternalW M=2 ret=1 Err=0x0 PID=1580(0x62c) App=C:\WINDOWS\System32\Wbem\wmic.exe Cmd=WMIC cpu get manufacturer CurDir=I:\PrayayaV3\Software\Program Files\Java\jre6\bin, (App=C:\WINDOWS\System32\Wbem\wmic.exe, Cmd=WMIC cpu get manufacturer, Wrk=I:\PrayayaV3\Software\Program Files\Java\jre6\bin)[     62c][     d8c][       0] Loadding v3hook.dll, lpReserved=0x0, C:\WINDOWS\System32\Wbem\wmic.exe[     62c][     d8c][       0] Connect V3Csr : 0x0
大家看,前边的数字代表进程号什么的,就是这个信息不是都是一行的,有的是两三行,四五行,所以什么readLine(),newLine()都无法用,不知道怎么按一条信息一条消息地读取?还有就是我有意在读取时去进行对象序列化,但是形如[XXX]的形式怎么读取里边的数字呢?StreamTokenizer这个类貌似这能一个字符一个字符的识别,所以譬如390,它给读成3,9,0,敬请各位大侠能就以上两个问题给小弟我支招。

解决方案 »

  1.   

    StreamTokenizer是可以做到的,可能是你的用法不对。
      

  2.   

    读取每条日志信息(从多行合并成一行), 逻辑基本上可以用下面这种方式处理: 
    void handleLogs() {
    // Init reader String log = "";
    String line = null; while ((line = reader.readLine()) != null) {
    log = handleLine(line, log); line = reader.readLine();
    if (line != null) {
    log = handleLine(line, log);
    }
    } if (log != null && log.startsWidth("[")) {
    handleLog(log);
    }
    }void handleLine(String line, String log) {
    if (line.startsWith("[")) {
    // 处理前一个log
    handleLog(log); log = line;
    } else {
    log += line;
    } return log;
    }void handleLog(String log) {
    ....
    }
      

  3.   

    写了个读取的日志, 会把多行日志给自动合并成一行, 读取数字就自己试试吧, 不难.
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class MergeMultiLineLog {
    void handleLogs() {
    try {
    BufferedReader reader = new BufferedReader(new FileReader("log.txt")); String log = "";
    String line = null; while ((line = reader.readLine()) != null) {
    log = handleLine(line, log); line = reader.readLine();
    if (line != null) {
    log = handleLine(line, log);
    }
    } if (log != null && log.startsWith("[")) {
    handleLog(log);
    }
    } catch (IOException ioex) {
    ioex.printStackTrace();
    }
    } String handleLine(String line, String log) {
    if (line.startsWith("[")) {
    // 处理前一个log
    handleLog(log); log = line;
    } else {
    log += line;
    } return log;
    } void handleLog(String log) {
    System.out.println(log);
    }

    public static void main(String[] args) {
    MergeMultiLineLog mmll = new MergeMultiLineLog();
    mmll.handleLogs();
    }
    }
      

  4.   

    读取文件,上io或者file中找找
      

  5.   

    感谢Inhibitory,几行读取的问题解决。剩下的我学学正则表达式的语法来做三个[]的匹配吧,多谢各位,散分结贴~