首页 > 解决方案 > 所以这是我的程序,但我不知道如何将 :40036 的所有数字仅重定向或仅重定向到新数据文件中?

问题描述

下面是 tcpprobe.dat 文件中的一些内容

100.006836647 10.10.1.2:40036 10.10.2.2:5001 32 0xf2037edc 0xf202ebcc 26 19 254848 152 29312
100.031193635 10.10.1.2:40036 10.10.2.2:5001 32 0xf2038a2c 0xf202f71c 26 19 254848 151 29312
100.140239621 10.10.1.2:40037 10.10.2.2:5001 32 0x20241c31 0x2023d851 13 11 186880 157 29312
100.152498003 10.10.1.2:40037 10.10.2.2:5001 32 0x20242781 0x2023ddf9 14 11 186880 156 29312
100.164485194 10.10.1.2:40037 10.10.2.2:5001 32 0x202432d1 0x2023e3a1 14 11 186880 155 29312
100.176630211 10.10.1.2:40037 10.10.2.2:5001 32 0x202432d1 0x2023e949 14 11 186880 154 29312
100.188673797 10.10.1.2:40035 10.10.2.2:5001 32 0x4fda1ee1 0x4fd9cfb1 15 13 336000 157 29312
100.200744133 10.10.1.2:40035 10.10.2.2:5001 32 0x4fda2a31 0x4fd9d559 15 13 336000 156 29312
100.212896515 10.10.1.2:40035 10.10.2.2:5001 32 0x4fda2a31 0x4fd9db01 15 13 336000 156 29312
100.225069255 10.10.1.2:40035 10.10.2.2:5001 32 0x4fda3581 0x4fd9e0a9 15 13 336000 155 29312
public class Process_TCPProbe_TP{ 


    public static void main(String[] args){

        try {
            Scanner scanner = new Scanner(new File("tcpprobe.dat"));
            scanner.useDelimiter(" ");
            while (scanner.hasNext()){
               System.out.print(scanner.next()+",");
            }//end of while  
        scanner.close();
        }//end of try  

        catch (IOException e) {
            System.out.println("File Read Error");
        }//end of catch

标签: java

解决方案


这里的一般方法是首先逐行读取文件。然后,在空白处分割每一行以隔离每个“数字”或术语。最后,打印所有包含 的数字:40036

try {
    File f = new File("tcpprobe.dat");
    BufferedReader b = new BufferedReader(new FileReader(f));

    String line = "";
    StringBuffer numbers = new StringBuffer();

    while ((line = b.readLine()) != null) {
        String[] parts = line.split("\\s+");
        for (String part : parts) {
            if (part.contains(":40036")) {
                if (numbers.length() > 0) numbers.append(",");
                numbers.append(part);
            }
        }
    }
}
catch (IOException e) {
    e.printStackTrace();
}

System.out.println(numbers);

编辑:

如果您想捕获每个完整的匹配行/语句,请使用此while循环:

while ((line = b.readLine()) != null) {
    String[] parts = line.split("\\s+");
    for (String part : parts) {
        if (part.contains(":40036")) {
            if (numbers.length() > 0) numbers.append(",");
            numbers.append(line);
            break;
        }
    }
}

推荐阅读