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

时间:2019-02-02 18:27:37

标签: java file input token

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

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

一个2 3三,四

5 6 7 8

我尝试在System.out.print(token)之后使用input2.next()或input2.nextline(),但是我遇到错误或者无法准确读取下一行。

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文件少,例如任何数目:

一二三四

5 6 8

3 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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();
      }
   }
}

答案 2 :(得分:0)

可能不是最佳选择,但它会起作用。每次循环迭代都会将当前行拆分为一个由数字(\\d+)分隔的字符串数组,然后将流传输每个数组元素(在这种情况下为字母和空格)并将其合并为单个字符串。 / p>

while (input2.hasNextLine()) {
    String[] nonNumbers = input2.nextLine().split("\\d+");
    System.out.println(Arrays.stream(nonNumbers).collect(Collectors.joining()));
}