[英]Extracting a number that occurs after a specific word from a longer text/file
我有5631
行的文本文件。 我想提取并存储出现在单词字节后面的数字
该文件中间的示例行形式如下:
debug3: In write loop, ack for 1606 32768 bytes at 52527104
在这里,我想要值52527104
。 此值每增加一行,我的目标是根据每行值计算完成百分比。 通过使用公式((obtained*100)/total)
。
谢谢。
您可以简单地将读取行按字节分割,并使用索引1
处的值。 我使用了Long
解析器,可以根据需要使用Integer
。 该代码将忽略不包含提供的模式的行。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class BytesAt {
public static void main(String[] args) throws FileNotFoundException {
Scanner read = new Scanner(new File("input.txt"));
while (read.hasNextLine()) {
String line = read.nextLine();
String parts[] = line.split("bytes at");
if(parts.length > 1) {
System.out.println("Value as String: " + parts[1].trim());
System.out.println("Value as Long: " + Long.parseLong(parts[1].trim()));
}
}
}
}
怎么样:
long totalBytes = //Whatever source.
long currValue = 0;
for (String line: lines) {
if (line.contains("bytes at")) {
long currValue = Long.parseLong(line.split("bytes at\\s")[1]);
}
System.out.println("Completed % = "+(float)(currValue/totalBytes*100);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.