有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java作为行的特定部分

嗨,我有一个包含跟踪路由和ping的日志文件。 我用手指把它们分开

if (scanner.nextLine ().startsWith ("64 bytes"){}

所以我现在可以只处理ping

我对ping感兴趣的是time=XX

示例数据行=

64 bytes from ziva.zarnet.ac.zw (209.88.89.132): icmp_seq=119 ttl=46 time=199 ms

我一直在阅读其他人提出的类似问题,我不知道如何应用到我的问题上

我确实需要的只是数字,因为我将把他们放入一个csv文件,这样我可以使数据的图表

编辑:使用robins解决方案,我现在在屏幕上看到我的ping被喷射出来,除了它每隔一次进行一次,并且错过了第一次

 while (scanner.hasNextLine ()) {
   //take only pings.
   if (scanner.nextLine ().startsWith ("64 bytes")){
       String line = scanner.nextLine ();       
       String pingAsString = line.substring (line.lastIndexOf ("=") + 1, (line.length () - "ms".length ()));
       Double ping = Double.valueOf (pingAsString);
       System.out.println ("PING AS STRING = "+ping);
   }
}

好的。这只需要移动线路分配。帽子。但是说得很清楚D


共 (3) 个答案

  1. # 1 楼答案

    尝试使用RegularExpression提取所需的数据:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class RegExTest {
        public static void main(String[] args) {
            String test = "line= 14103 64 bytes from ziva.zarnet.ac.zw (209.88.89.132): icmp_seq=119 ttl=46 time=199 ms";
    
            // build the regular expression string
            String regex = ".*time=(\\d+).*";
    
            // compile the regular expresion into a Pattern we can use on the test string
            Pattern pattern = Pattern.compile(regex);
    
            Matcher matcher = pattern.matcher(test);
    
            // if the regular expression matches, grab the value matching the
            // expression in the first set of parentheses: "(\d+)"
            if (matcher.matches()) {
                System.out.println(matcher.group(1));
            }
        }
    }
    
  2. # 2 楼答案

    或者,如果不想执行reg ex magic,您可以使用String上的可用方法

    String line = ...
    String pingAsString = line.substring( line.lastIndexOf("=")+1, (line.length() - " ms".length() ) );
    Integer ping = Integer.valueOf( pingAsString );
    
  3. # 3 楼答案

    Scanner scanner = new Scanner (new File ("./sample.log")); 
    while (scanner.hasNext ())
    {
        String line = scanner.nextLine (); 
        if (line.startsWith ("64 bytes")) {
             String ms = line.replaceAll (".*time=([0-9]+) ms", "$1");
             System.out.println ("ping = " + ms); 
        } // else System.out.println ("fail " + line); 
    }
    

    你的问题是,你称之为:

    if (scanner.nextLine ().startsWith ("64 bytes")){
    

    这意味着该行被抓取,但未指定给变量。结果立即被测试为startingWith,但随后您再次调用nextLine,并获得下一行,当然:

       String line = scanner.nextLine ();      
    

    这是第二行