繁体   English   中英

如何从txt文件中打印特定数字?

[英]How to print specific numbers from txt file?

我有一个用以下文本编写的文本文件:


18275440:Annette Nguyen:98 
93840989:Mary Rochetta:87 
23958632:Antoine Yung:79 
23658231:Claire Coin:78 
23967548:Emma Chung:69 
23921664:Jung Kim:98 
23793215:Harry Chiu:98

我想从每一行中提取最后两位数字。 这是我写的代码:

for (int i = 3; i < 25; i++) {
    line = inFile.nextLine();
    String[] split = line.split(":");
    System.out.println(split[2]);
}

我收到运行时错误。

更新阅读方法,如果您使用的是Scanner您可以检查是否还有剩余的行。

while(inFile.hasNextLine()) {
    line = inFile.nextLine();
    String[] split = line.split(":");
    System.out.println(split[2]);
}

为什么for循环规范如此复杂? 你不使用i ,所以为什么要费心呢。 你不是只想读几行直到没有更多行了吗? 如果你这样做,假设inFile会让你从中读取行,你的代码实际上解析每一行并在最后提取数字似乎是正确的。 这是一个完整的(减去类定义)示例,它使用您的解析逻辑:

public static void main(String[] args) throws IOException {

    // Open the input data file
    BufferedReader inFile = new BufferedReader(new FileReader("/tmp/data.txt"));

    while(true) {
        // Read the next line
        String line = inFile.readLine();

        // Break out of our loop if we've run out of lines
        if (line == null)
            break;

        // Strip off any whitespace on the beginning and end of the line
        line = line.strip();

        // If the line is empty, skip it
        if (line.isEmpty())
            continue;

        // Parse the line, and print out the third component, the two digit number at the end of the line
        String[] split = line.strip().split(":");
        System.out.println(split[2]);
    }
}

如果有一个名为/tmp/data.txt的文件包含您在问题中提供的内容,这就是您从此代码获得的输出:

98
87
79
78
69
98
98

不要对您的循环标准如此明确。 使用计数器从文件中获取您想要的数据,例如:

int lineCounter = 0;
String line;
while (inFile.hasNextLine()) {
    line = inFile.nextLine();
    lineCounter++;
    if (lineCounter >=3 && lineCounter <= 24) {
        String[] split = line.trim().split(":");
        System.out.println(split[2]);
    }
} 

假设您使用的是 Java 8,您可以通过使用 BufferedReader 的lines方法采取一种更简单、命令性较低的方法,该方法返回一个 Stream:

BufferedReader reader = new BufferedReader(new FileReader("/tmp/data.txt"));
reader.lines()
      .map(line -> line.split(":")[2])
      .forEach(System.out::println);

但是,想想看,您可以通过使用来自 Java 的 NIO API 的文件来避免 BufferedReader:

Files.lines(Paths.get("/tmp/data.txt")) 
      .map(line -> line.split(":")[2])
      .forEach(System.out::println);

我不知道为什么你的代码会出错。 如果您在开始时有任何不需要的行(我看到您的代码中有 3 行这样的行),只需在它们上运行一个空扫描仪。

Scanner scanner = new Scanner(new File("E:\\file.txt"));

String[] split;
    
// run an empty scanner
for (int i = 1; i <= 3; i++) scanner.nextLine();

while (scanner.hasNextLine()) {
    split = scanner.nextLine().split(":");
    System.out.println(split[2]);
}

如果您不知道这样的线路并且它们不符合线路规则,那么您可以使用 try...catch 来消除它们。 我在这里使用了一个简单的例外。 但是当您的条件不满足时,您可能会抛出异常。

假设您的文件如下所示:

1
2
3
18275440:Annette Nguyen:98 
93840989:Mary Rochetta:87 
23958632:Antoine Yung:79 
bleh bleh bleh
23658231:Claire Coin:78 
23967548:Emma Chung:69 
23921664:Jung Kim:98 
23793215:Harry Chiu:98

那么你的代码将是

Scanner scanner = new Scanner(new File("E:\\file.txt"));

String[] split;

// run an empty scanner
// for (int i = 1; i <= 3; i++) scanner.nextLine();

while (scanner.hasNextLine()) {
    split = scanner.nextLine().split(":");
    try {
        System.out.println(split[2]);
    } catch (ArrayIndexOutOfBoundsException e) {
    }
}

您可以拆分\\d+:[\\p{L}\\s]+:并从结果数组中取出第二个元素。 正则表达式模式\\d+:[\\p{L}\\s]+:表示一串数字 ( \\d+ ) 后跟一个: ,然后是一个字母和空格的任意组合的字符串,依次是后跟一个:

public class Main {
    public static void main(String[] args) {
        String line = "18275440:Annette Nguyen:98";
        String[] split = line.split("\\d+:[\\p{L}\\s]+:");
        String n = "";
        if (split.length == 2) {
            n = split[1].trim();
        }
        System.out.println(n);
    }
}

输出:

98

请注意, \\p{L}指定了一个字母

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM