我怎样才能让我的扫描仪读取文件中的下一行?

问题描述 投票:1回答:3

我打印出一个txt文件的内容,跳过那些文件中的任何数字。

我使用看起来像这样的文件:

一二3三,四

五六7 8

我一直在使用input2.next()或input2.nextline()是System.out.print后(令牌)试过,但我要么得到一个错误或不准确的读取下一行。

import java.util.*;
import java.io.*;


public class ScannerClass {


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


    System.out.print("Enter file name and extension: ");

    Scanner input = new Scanner(System.in);

    File file = new File(input.next());

    Scanner input2 = new Scanner(file);


    String token;

//this will print out the first line in my txt file, I am having trouble
//reading the next line in the file!

    while ((token = input2.findInLine("[\\p{Alpha}\\p{javaWhitespace}]+")) != null) {
        System.out.print(token);


    }

  }
}

输出是:

一二三四

我想看到的是整个txt文件少任何数字,如:

一二三四

五六8

java file input token
3个回答
1
投票

你REG EXP一个主要问题是,它首先是位前,然后只有一个行的一部分相匹配的数字之后,而findInLine莫名其妙地前进行计数器。

因此,这里是使用REG EXP模式的不同的解决方案,但我从匹配逻辑分离从文件读取

Pattern p = java.util.regex.Pattern.compile("[\\p{Alpha}\\p{javaWhitespace}]+");
while (input2.hasNextLine()) {
    String line = input2.nextLine();
    Matcher m = p.matcher(line);
    while (m.find()) {
        System.out.print(m.group()); //Prints each found group
    }
    System.out.println();
}

0
投票

您可以添加此正则表达式;

import java.util.*;
import java.io.*;

public class ScannerClass {
    public static void main(String[] args) throws FileNotFoundException {
       System.out.print("Enter file name and extension: ");
       Scanner reader = new Scanner(System.in);
       reader = new Scanner(new File(reader.next()));

       Pattern p = Pattern.compile("[a-zA-Z_]+");
       Matcher m = null;

       while (reader.hasNext()){
          String nextLine = reader.nextLine();
          m = p.matcher(nextLine);
          while(m.find()) {
              System.out.printf("%s ",m.group());
          }
          System.out.println();
      }
   }
}

0
投票

可能不是最优化,但它会工作。每次循环迭代将分裂当前行到由号码(\\d+)分隔的一个字符串数组,则每个数组元素(字母表字和空白在这种情况下)将被流传输和连接成一个字符串。

while (input2.hasNextLine()) {
    String[] nonNumbers = input2.nextLine().split("\\d+");
    System.out.println(Arrays.stream(nonNumbers).collect(Collectors.joining()));
}
© www.soinside.com 2019 - 2024. All rights reserved.